PayPal · Question 51 · Heaps
Top K Frequent Elements
Problem
Return the k most frequent elements from an array.
Approach
Use a frequency map and a min - heap priority queue to track top k elements.
Time O(nlogk)Space O(n)
How it works
- 1Count frequencies.
- 2A size-k min-heap keeps the top entries, most frequent last polled.
Sample input / output
Input: nums = [1, 1, 1, 2, 2, 3], k = 2 Output: [1, 2]
Constraints
Answer unique; any order accepted by the judge; driver prints most-frequent-first.
Solution — read it, then walk it
Time O(nlogk)Space O(n)Loops 3Branches 1Returns 1source · Java
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