Top K Frequent Elements
Beginner Mode

Problem Statement

Given an integer array nums and an integer k, return the k most frequent elements in the array.

The answer is guaranteed to be unique, and you may return the output in any order.

Additional information

  • 1 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000
  • 1 <= k <= number of distinct elements in nums

Example 1:

Input: nums = [1, 1, 1, 2, 2, 3], k = 2

Output: [1, 2]

Explanation: The number 1 appears 3 times and 2 appears 2 times. These are the two most frequent elements.

Example 2:

Input: nums = [1], k = 1

Output: [1]

Example 3:

Input: nums = [1, 2, 3], k = 3

Output: [1, 2, 3]

Explanation: Every element appears exactly once, so all three are returned.

Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →