Back to All Questions
Top K Frequent Elements
Flipkart
Array
Hash Table
Heap
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Example:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Solution Walkthrough
This combines a frequency count with a bounded min-heap, the same "keep only the top k" pattern used in the Kth Largest Element problem.
- Build a hash map counting how many times each number appears in
nums. - Push
[count, number]pairs from the map onto a min-heap ordered bycount. - Whenever the heap grows past size
k, pop its minimum — this discards the least frequent candidates first, so only thekmost frequent numbers can survive. - Once every distinct number has been processed, the heap contains exactly the
kmost frequent elements. Extract their values.
Counting takes O(n). With d distinct numbers, maintaining a heap bounded at size k costs O(d log k). This beats sorting all distinct counts (O(d log d)) whenever k is small relative to d.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
Related Algorithms