Find Top K Frequent Elements in an Array (Hash Map + Bucket Sort)
Problem Statement
Given an integer array `nums` and an integer `k`, return the `k` most frequent elements in O(N) time complexity. You may return the answer in any order.
Target Complexity
Time:
O(N) with Bucket Sort (or O(N log K) with Min-Heap)
Space:
O(N) for frequency map and buckets
Interview Talking Points:
- • Explain why sorting the map entries takes O(N log N), while Bucket Sort achieves optimal O(N) linear time.
- • Explain the Min-Heap approach for streaming data where total size N is unknown in advance.
Solution Editor (JavaScript)
Ready to run
Test Results
Returns top 2 frequent elements from array
Test #1Handles single element array
Test #2Handles negative numbers and distinct frequencies
Test #3