MEDIUM NC#5 Blind #74 Arrays & Hashing
347. Top K Frequent Elements
๐ Problem
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. It is guaranteed that the answer is unique. Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Count frequency of each element
- โ Use bucket sort where index = frequency
- โ Each bucket contains elements with that frequency
- โ Collect elements starting from highest frequency buckets
- โ Time: O(n), Space: O(n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขCount frequency of each element
- โขUse bucket sort where index = frequency
- โขEach bucket contains elements with that frequency
Common Pitfalls
- โขCollect elements starting from highest frequency buckets
- โขTime: O(n), Space: O(n)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
topKFrequent([1,1,1,2,2,3], 2); Expected:
[1, 2] Test Case 2
Not run Input:
topKFrequent([1], 1); Expected:
[1] Test Case 3
Not run Input:
topKFrequent([4,1,-1,2,-1,2,3], 2); Expected:
[-1, 2] ๐ Code Editor
๐ค Output