Dashboard
#5. Top K Frequent ElementsMediumArrays & Hashing

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

The test cases are generated such that the answer is always unique.

You may return the output in any order.

Example 1:

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

Output: [2,3]

Example 2:

Input: nums = [7,7], k = 1

Output: [7]

Constraints:

  • 1 <= nums.length <= 10^4.
  • -1000 <= nums[i] <= 1000
  • 1 <= k <= number of distinct elements in nums.
Examples
Example 1:
Input: nums = [1,2,2,3,3,3], k = 2
Output: [2,3]
Example 2:
Input: nums = [7,7], k = 1
Output: [7]
Constraints
  • `1 <= nums.length <= 10^4`.
  • `-1000 <= nums[i] <= 1000`
  • `1 <= k <= number of distinct elements in nums`.
Prerequisites
  • Hash Usage(Data Structures & Algorithms for Beginners)
  • Bucket Sort(Data Structures & Algorithms for Beginners)
Target: O(N) time • O(1) spaceArray / Hash Table / Divide and Conquer / Sorting / Heap (Priority Queue) / Bucket Sort / Counting / Quickselect
Socratic AI Tutor
Gemini 3.8 Flash
Loading editor...

Click "Run" or press Ctrl+Enter to execute test cases.