InterviewPrepKit

Home / Coding / Arrays & Hashing

Top K Frequent Elements

medium Original β†—
Solving tips
  • Step one is always a hash-map count; the interesting part is selecting the top k without a full O(n log n) sort.
  • For true O(n), bucket by frequency: buckets[f] holds values occurring f times (f ranges 1..n), then sweep f from n down to 1 collecting values until you have k.
  • A size-k min-heap gives O(n log k) and is the go-to when k is small or data streams; keep the k largest by evicting the root (smallest).
  • Pitfall: size the bucket array to n+1 (a value can occur n times), and use a MIN-heap so you evict the smallest frequency.

Problem

Given an integer array nums and an integer k, return the k values that occur most often in nums. The answer may be returned in any order, and it is guaranteed to be unique (no ties that would make the choice ambiguous).

Follow-up: your algorithm should beat O(n log n) β€” i.e. do better than β€œsort everything by frequency”.

Examples

Example 1: nums = [1, 1, 1, 2, 2, 3], k = 2 β†’ [1, 2] 1 appears three times and 2 twice; 3’s single occurrence loses.

Example 2: nums = [1], k = 1 β†’ [1] Only one distinct value.

Example 3: nums = [4, 4, 4, 5, 5, 6], k = 1 β†’ [4] 4 is the unique most frequent element.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is between 1 and the number of distinct elements; the answer is unique.

n up to 10^5 makes counting cheap; the interesting part is selecting the top k without a full O(n log n) sort.

Think about it first

Hint 1 Step one is always the same: how do you get every element's frequency in one pass?
Hint 2 You need the k largest frequencies, not a full ranking. Which data structure extracts "k largest" while only ever holding k items?
Hint 3 For true O(n): a frequency can only be 1..n. Make a bucket per frequency (`buckets[f]` = values occurring f times), then read buckets from n down to 1 until you've collected k values β€” an application of counting/bucket sort.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.