heaps · Problem 2 of 2
Top K Frequent Elements
medium
Amazon
Meta
Google
Microsoft
Netflix
Given an integer array nums and an integer k, return the k most frequent elements. Return the result sorted in descending order of frequency (or ascending value if tied).
topKFrequent([1, 1, 1, 2, 2, 3], 2) -> [1, 2]
topKFrequent([1], 1) -> [1]
topKFrequent([4, 1, -1, 2, -1, 2, 3], 2) -> [-1, 2]Your solution
Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.
Running is free — Submit is what records it. Or press ⌘↩
Tests
4 cases, 1 hidden| call | type | expected | result |
|---|---|---|---|
| topKFrequent([1,1,1,2,2,3], 2) | top 2 frequent | [1,2] | — |
| topKFrequent([1], 1) | single element | [1] | — |
| topKFrequent([4,1,-1,2,-1,2,3], 2) | negative numbers tied | [-1,2] | — |
| withheld | hidden | withheld | — |
Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.
Complexity
- target time
- O(n)
- target space
- O(n)
Using bucket sort achieves O(n) linear time complexity; min-heap approach achieves O(n log k).
Hints
Stuck? Hints open one at a time, each giving a little more away.
3 hints left