ToolMight Logo
MediumArrays & HashingHeap & Priority QueueBucket SortFrequency Map

Top K Frequent Elements

Extract the k most frequent integers in an array. Compare a size-K Min-Heap over frequency counts with O(n) frequency-indexed Bucket Sort.

Optimal Time
O(n)
Optimal Space
O(n)
Primary Pattern
Bucket Sort
Visualizer
Open Interactive View →

Problem Statement

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Examples & Constraints

Example 1
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
Explanation: 1 appears three times, 2 appears twice, and 3 appears once. The 2 most frequent numbers are [1, 2].
Example 2
Input: nums = [1], k = 1
Output: [1]
Explanation: 1 is the only element, so it is the most frequent.
Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Top-K frequency queries drop below O(n log n) sorting either with a size-K Min-Heap (`O(n log k)`) or by inverting counts into frequency-indexed buckets (`O(n)`).

Core Invariant

No single integer can appear more than N times in a length-N array, so indexing buckets[freq] across 1..N places counts in sorted order without a comparison sort.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Frequency Map + Bounded Size-K Min-Heap
O(n log k)O(n)Count frequencies in a hash map, then stream (freq, num) pairs through a Min-Heap capped at capacity k in O(n log k) time.
2. Bucket Sort by Frequency (Linear O(n) Time)Optimal
O(n)O(n)Count frequencies in a hash map. Group numbers into buckets indexed by their frequency count (0 to n). Iterate backwards from the highest frequency bucket to collect the top k elements in O(n) time.

1. Frequency Map + Bounded Size-K Min-Heap

TimeO(n log k)
SpaceO(n)

Count frequencies in a hash map, then stream (freq, num) pairs through a Min-Heap capped at capacity k in O(n log k) time.

Time ComplexityO(n log k)

Building frequency map is O(n); pushing up to n unique keys through a size-k heap takes O(n log k).

Space ComplexityO(n)

Frequency map stores up to n keys plus O(k) heap space.

How It Works

Bounded Priority Selection Over Frequencies

After counting occurrences per distinct value in O(n), keeping only the top k pairs is identical to Kth Largest Element:

  1. Build counts[val] across nums.
  2. Push each (freq, val) into a Min-Heap ordered by freq.
  3. Whenever heap.size > k, pop the smallest frequency entry.
  4. Collect all remaining keys in the heap (O(n log k), which stays near-linear when k << n).

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Count Frequencies

[1, 1, 1, 2, 2, 3] yields frequency pairs (3, 1), (2, 2), (1, 3).

State:counts = {1: 3, 2: 2, 3: 1}
Strengths
  • +Beats O(n log n) sorting whenever k is small
  • +Clean priority-queue pattern
Trade-offs
  • -Slightly slower than O(n) Bucket Sort when k approaches n

Reference Implementation

Complete implementation for Frequency Map + Bounded Size-K Min-Heap in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
import heapq
from collections import Counter
def top_k_frequent_heap(nums: list[int], k: int) -> list[int]:
counts = Counter(nums)
min_heap: list[tuple[int, int]] = []
for num, freq in counts.items():
heapq.heappush(min_heap, (freq, num))
if len(min_heap) > k:
heapq.heappop(min_heap)
return [num for _, num in min_heap]

2. Bucket Sort by Frequency (Linear O(n) Time)

Optimal
TimeO(n)
SpaceO(n)

Count frequencies in a hash map. Group numbers into buckets indexed by their frequency count (0 to n). Iterate backwards from the highest frequency bucket to collect the top k elements in O(n) time.

Time ComplexityO(n)

Building the frequency map takes O(n). Distributing items into buckets takes O(n). Scanning the buckets from N down to 1 takes O(n). Total runtime is strictly linear O(n).

Space ComplexityO(n)

Consumes memory for the frequency hash map and the bucket array of size N + 1.

How It Works

Why Sort by Frequency Can Be O(n)

Usually, sorting items by their frequency takes O(m log m) where M is the number of unique elements.

However, notice a crucial frequency constraint:

  • An element can appear at most N times (the total length of the array).
  • Therefore, the possible frequencies are integers bounded between 1 and N.

When values are bounded integers, we can use Bucket Sort!

The Bucket Sort Algorithm:

  1. Count Frequencies:
  • Use a Hash Map to count occurrences of each number: counts[num] = count.
  1. Create Buckets:
  • Create an array of lists buckets of size n + 1.
  • buckets[freq] stores all numbers that appeared exactly freq times.
  • For example, if number 1 appeared 3 times, place 1 in buckets[3].
  1. Collect Top K from Right to Left:
  • Traverse buckets starting from index n down to 1 (highest frequency first).
  • Append numbers from each non-empty bucket to our result list until we have collected k elements.
  1. Return the result list in guaranteed linear O(n) time!

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1nums = [1, 1, 1, 2, 2, 3], k = 2

Count frequencies using hash map: {1: 3, 2: 2, 3: 1}.

State:counts: 1 -> 32 -> 23 -> 1
Strengths
  • +Optimal O(n) runtime beating traditional O(n log n) sorting
  • +Straightforward bucket array traversal
Trade-offs
  • -Consumes O(n) auxiliary memory for buckets array

Reference Implementation

Complete implementation for Bucket Sort by Frequency (Linear O(n) Time) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def top_k_frequent(nums: list[int], k: int) -> list[int]:
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
# buckets[i] stores numbers that appear i times
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
res = []
for freq in range(len(nums), 0, -1):
for num in buckets[freq]:
res.append(num)
if len(res) == k:
return res
return res
if __name__ == "__main__":
test1 = [1, 1, 1, 2, 2, 3]
k1 = 2
test2 = [1]
k2 = 1
print("test1 top 2:", top_k_frequent(test1, k1))
print("test2 top 1:", top_k_frequent(test2, k2))
Interactive Visualizer

Trace Hash Table mechanics in memory

Step through custom inputs in the Hash Table visualizer to inspect pointer updates, array shifts, and call-stack state alongside Top K Frequent Elements.

Open Hash Table visualizer

Frequently Asked Questions

Why is Bucket Sort faster than sorting by frequency?

Comparison-sorting unique elements by frequency costs O(m log m). Since every element's frequency lies in 1..n, indexing buckets[freq] bins counts into sorted frequency order in O(n) linear time.

Can we solve this with a Min-Heap instead?

Yes. Maintain a Min-Heap of capacity k ordered by frequency (O(n log k) time, O(n) map space). It works well even if frequencies weren't small bounded integers.

Why must `buckets` have size `nums.length + 1` instead of `nums.length`?

If all n elements in nums are equal (e.g., [5, 5, 5]), that value has frequency n, which requires buckets[n] to exist cleanly without an out-of-bounds error.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Single-element or uniform array ([1], k = 1 or [7, 7, 7], k = 1) sets freq == nums.length, requiring buckets of size nums.length + 1.
  • Negative integers ([-1, -1, -2, -2, -2, 3], k = 1) require offsetting array keys if indexing fixed counts in C.
  • k equals the number of distinct elements returns all unique numbers.

Common Bugs to Avoid

  • Allocating `buckets` of length `n` instead of `n + 1`, hitting IndexError/out-of-bounds when all elements are identical (frequency = n).
  • Picking a Max-Heap of size M instead of a Min-Heap of size K, increasing space/push complexity from O(log k) to O(log m).
  • Forgetting to stop collecting once `res.length == k` when multiple elements share a lower-tie bucket.

Interview Follow-Up Variations

  • Top K Frequent Words: tie-break equal frequencies alphabetically using a custom comparator in a size-K Min-Heap.
  • Sort Characters By Frequency: aggregate character counts across 128 ASCII chars and emit descending by bucket frequency.

Related Problems

All problems
EasyArrays & Hashing

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Pattern: Hash Set
O(n) · O(n)
Solve
MediumHeap & Priority Queue

Kth Largest Element in an Array

Locate the kth largest integer in an unsorted array without full sorting. Compare a size-K streaming Min-Heap with average-O(n) Randomized Quickselect.

Pattern: Min-Heap Top-K
O(n log k) · O(k)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve