Skip to content

Top K Frequent Elements

MediumLeetCode #347Time O(n)Space O(n)

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)

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 result
  • Time: O(n) — one pass to count, one to fill buckets, one walk over at most n + 1 buckets that visits each distinct number once.
  • Space: O(n) — the count map, and n + 1 buckets holding at most n numbers in total.
  • Make n + 1 buckets, not n. A number appearing in every position has count n, so index n must exist. Index 0 is never used.
  • Stop as soon as you have k numbers. 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 at k entries, popping the smallest when it grows past k. O(n log k) time, O(n) space. Use it if the interviewer says the data is a stream or k is tiny.

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.

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).

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.