Google · Question 12 · Heaps
Top K Frequent Elements
Problem
Return the k most frequent elements in the array.
Approach
Use a hashmap for frequency count and a heap to extract the top k.
Time O(nlogk)Space O(n)
How it works
- 1Count the frequency of each element using Counter.
- 2Use heapq.nlargest to get the top k keys by frequency.
- 3Return those keys.
- 4This finds the top k without sorting the entire list.
Sample input / output
Input: 6 2 1 1 1 2 2 3 Output: [1, 2]
Constraints
1 <= nums.length <= 10^5; -10^4 <= nums[i] <= 10^4; 1 <= k <= unique elements; answer is unique.
Solution — read it, then walk it
Time O(nlogk)Space O(n)Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/15
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits