Top K Frequent Elements
The problem
Section titled “The problem”You get an integer array and a number k. Return the k values that occur most often,
in any order. The answer is guaranteed to be unique.
nums = [1, 1, 1, 2, 2, 3], k = 2 -> [1, 2] (1 appears 3 times, 2 appears twice)Key insight
Section titled “Key insight”Counting is easy with a hash map. The question is how to pick the top k counts.
Sorting the counts costs O(n log n). A min-heap of size k costs O(n log k) and is a
fine answer to give an interviewer first.
To reach O(n), notice that a count can never exceed n. So use the count itself as an
array index: buckets[f] holds every number that appears exactly f times. This is
bucket sort. Walk the buckets from n down to 1 and collect numbers until you have k.
Show solutionHide solution
from collections import Counter
def top_k_frequent(nums: list[int], k: int) -> list[int]: count = Counter(nums) # buckets[f] holds the numbers that appear exactly f times buckets = [[] for _ in range(len(nums) + 1)] for num, freq in count.items(): buckets[freq].append(num)
result = [] for freq in range(len(nums), 0, -1): # most frequent first for num in buckets[freq]: result.append(num) if len(result) == k: return result return resultexport function topKFrequent(nums: number[], k: number): number[] { const count = new Map<number, number>(); for (const num of nums) count.set(num, (count.get(num) ?? 0) + 1);
// buckets[f] holds the numbers that appear exactly f times const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []); for (const [num, freq] of count) buckets[freq].push(num);
const result: number[] = []; for (let freq = nums.length; freq > 0; freq--) { // most frequent first for (const num of buckets[freq]) { result.push(num); if (result.length === k) return result; } } return result;}import java.util.*;
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> count = new HashMap<>(); for (int num : nums) count.merge(num, 1, Integer::sum);
// buckets[f] holds the numbers that appear exactly f times List<Integer>[] buckets = new List[nums.length + 1]; for (int i = 0; i < buckets.length; i++) buckets[i] = new ArrayList<>(); for (Map.Entry<Integer, Integer> e : count.entrySet()) { buckets[e.getValue()].add(e.getKey()); }
int[] result = new int[k]; int size = 0; for (int freq = nums.length; freq > 0 && size < k; freq--) { // most frequent first for (int num : buckets[freq]) { if (size == k) break; result[size++] = num; } } return result; }}Complexity
Section titled “Complexity”- Time: O(n) — one pass to count, one to fill buckets, one walk over at most
n + 1buckets that visits each distinct number once. - Space: O(n) — the count map, and
n + 1buckets holding at mostnnumbers in total.
Watch out for
Section titled “Watch out for”- Make
n + 1buckets, notn. A number appearing in every position has countn, so indexnmust exist. Index 0 is never used. - Stop as soon as you have
knumbers. One bucket can hold several numbers, so check the size inside the inner loop, not once per bucket. - Heap alternative: keep a min-heap of
(count, value)capped atkentries, popping the smallest when it grows pastk. O(n log k) time, O(n) space. Use it if the interviewer says the data is a stream orkis tiny.
Variations
Section titled “Variations”Sort Characters By Frequency (LeetCode 451)
Section titled “Sort Characters By Frequency (LeetCode 451)”Rearrange a string so the most frequent characters come first. The trick: the same
count-then-bucket idea, then emit each character repeated count times, from the
highest bucket down.
Top K Frequent Words (LeetCode 692)
Section titled “Top K Frequent Words (LeetCode 692)”Same as this problem, but for words, and ties go in alphabetical order. The trick:
bucketing no longer gives the tie order for free. Sort or use a heap keyed by
(-count, word).
K Closest Points to Origin (LeetCode 973)
Section titled “K Closest Points to Origin (LeetCode 973)”Return the k points nearest to (0, 0). The trick: a size-k max-heap on squared
distance (no square root needed), or quickselect for O(n) average time.