InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Top K Frequent Elements

medium Original ↗ 00:00

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 appears once and is excluded.

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.

With n up to 10^5, counting is cheap; the challenge is selecting the top k without a full O(n log n) sort.

Think about it first

Hint 1 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug