Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Top K Frequent Elements

Heapsmedium

Implement `topKFrequent(nums, k)` that returns the `k` most frequent elements. Return them ordered by frequency (highest first); break ties by the smaller value first.

Examples

Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
1 appears 3 times, 2 appears twice.
Input: nums = [4, 4, 5, 5, 6], k = 1
Output: [4]
4 and 5 tie at 2 occurrences; the smaller value 4 wins.

Sample tests

Input: topKFrequent([1,1,1,2,2,3], 2)
Output: [1,2]
Input: topKFrequent([4,4,5,5,6], 1)
Output: [4]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Relying on Map/object key insertion order instead of an explicit sort gives inconsistent results across inputs.

Learning resources

  • Wikipedia: Binary heap
  • Wikipedia: Hash table
Approach & explanation (try first)

A hash map counts occurrences in O(n). Sorting the distinct keys by frequency (then by value to make the order deterministic) and slicing the first k yields the answer. A real interview answer can replace the full sort with a size-k heap for O(n log k).

Loading...
⌘/Ctrl + Enter

Run your code to see results.