Browse curriculum

Top K Frequent Elements

Return the k most frequent values in an array in O(n) with a count map and buckets indexed by frequency.

Problem Understanding

Top K Frequent Elements: given an integer array nums and an integer k, return the k values that appear most often, in any order. The answer is guaranteed to be unique.

Example: nums = [1, 1, 1, 2, 2, 3], k = 2 returns [1, 2] — 1 appears three times and 2 twice.

Attempt 1: Count, Then Sort by Count

Count every value with a hash map, sort the distinct values by their count in descending order, and take the first k. Counting is O(n), but sorting the m distinct values costs O(m log m) — up to O(n log n). The count map is the right first step; the sort is the part to replace.

The Intuition: Counts Are Small Integers

A value can appear at most n times, so its count is an integer from 1 to n. That means counts can be used as array indexes instead of being sorted:

  1. Count every value in a hash map.
  2. Make buckets 0..n; put each value into buckets[count].
  3. Walk the buckets from n down to 1, taking values until k have been taken.

Every step is linear, so the whole method is O(n) — the same idea as bucket sort, applied to frequencies.

Interactive Walkthrough

k = 2

START

nums

1

0

1

1

1

2

2

3

2

4

3

5

Result

—

count (value:count)

Empty

 

Find the 2 most frequent values. The count map starts empty

Next

nums[0] = 1: count[1] is now 1

Array

Target

First the array is counted left to right while the count map grows beside it. Then the buckets appear, one row per count from the highest down, and are read from the top; each value taken lights up and joins the result.

The approach, step by step

  1. Count

    Count each value's occurrences in a hash map.

  2. Bucket by count

    Put each value into buckets[count], with buckets 0..n.

  3. Read from the top

    Walk the buckets from n down to 1, collecting values until k have been taken.

Frequently asked questions

How do you find the top k frequent elements in O(n)?

Count every value with a hash map. Make buckets indexed 0..n, where bucket f holds the values seen exactly f times, since no value appears more than n times. Read the buckets from n down to 1 and stop after taking k values.


When is a heap the better choice?

A min-heap of size k gives O(n log k) and only needs O(k) extra space beyond the counts, which suits a stream or a very large n. Bucketing is O(n) but allocates n + 1 buckets. Both start from the same count map.


What happens when values tie on frequency?

Tied values share a bucket. LeetCode guarantees the answer is unique, so a tie never straddles the k-th place; in general you would take any of the tied values.