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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit