Forward Deployed EngineeringCodingHash Maps and Heaps
Top-K frequent elements
Question 36 of 73 · Updated
On this page
- Interview-ready answer
- 1. Define the contract
- 2. Counting is the shared first step
- 3. Approach A: sort the distinct values
- Dry run
- Correctness
- Complexity
- 4. Approach B: bounded min-heap
- Dry run with replacements
- Correctness proof using an invariant
- Complexity
- 5. Approach C: frequency buckets
- Dry run
- Correctness
- Complexity
- 6. Compare the algorithms
- 7. Edge cases and mistakes
- 8. Local implementation verification
- 9. Production and FDE considerations
- Likely interviewer follow-ups
- Interview takeaway
Interview-ready answer#
I would first count every distinct element using a hash map. Then I would select the k elements with the highest frequencies. If k is small compared with the number of distinct values, a size-k min-heap is a good choice: the root represents the weakest retained candidate, and a stronger candidate replaces it. Counting takes expected O(n) time, and heap selection takes O(u log(k + 1)) time, where u is the number of distinct elements.
For a finite array, frequencies are integers between 1 and n. This lets me use buckets indexed by frequency instead of comparison sorting. I place each distinct value into its frequency bucket and scan the buckets in descending order until I have k elements. That gives expected O(n) time with O(n) auxiliary space. Sorting the u distinct values by frequency is also a simple baseline.
Before coding, I would clarify whether ties can be broken arbitrarily, whether the output must be ordered, and how invalid k values should be handled.
1. Define the contract#
Given a list of integers nums and an integer k, return k distinct values with the highest occurrence counts. The implementations here use a deterministic extension of the usual interview contract:
- Return values, not indices or frequencies.
- Return values in descending frequency order.
- Break ties using first appearance in the original input.
- Allow k = 0, returning an empty list.
- Raise ValueError when k is negative or exceeds the number of distinct values.
- Leave the input unchanged.
Assume nums is a list of integers and k is an integer. The classic problem may guarantee a unique set of k most frequent values and allow any output order. The explicit tie rule here makes all three implementations comparable even when that guarantee does not hold.
| Input | k | Result |
|---|---|---|
| [1,1,1,2,2,3] | 2 | [1,2] |
| [4,8,8,4,9] | 2 | [4,8] |
| [-1,-1,0,2] | 1 | [-1] |
| [7,7,7] | 1 | [7] |
| [] | 0 | [] |
For the second example, both 4 and 8 occur twice. The value 4 appears first, so it ranks ahead of 8. The tie rule is applied at the selection boundary as well as in the returned order.
2. Counting is the shared first step#
For nums = [1,1,1,2,2,3], the count map contains:
| Value | Frequency |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 1 |
Python's Counter counts elements and retains insertion order for keys in modern Python. Each key corresponds to a distinct value, so the selection stage never returns an element more than once.
The count stage takes expected O(n) time and O(u) auxiliary space under ordinary hash-table assumptions. All three approaches use this same frequency table, but differ in how they select the highest-ranked entries.
3. Approach A: sort the distinct values#
Sort the dictionary keys by frequency in descending order, then take the first k. Python sorting is stable, including with reverse=True, so equal-frequency entries retain their original key order.
PYTHONfrom collections import Counter def topk_sort(nums, k): counts = Counter(nums) if not 0 <= k <= len(counts): raise ValueError('k outside distinct-value count') return sorted(counts, key=counts.get, reverse=True)[:k]
Dry run#
For nums = [4,8,8,4,9] and k = 2:
- Count the values in first-occurrence order: 4 → 2, 8 → 2, 9 → 1.
- Stable descending sort by frequency produces [4,8,9].
- Return the first two values: [4,8].
Correctness#
Sorting produces a total order under the declared ranking: greater frequency first, earlier appearance first on ties. Every element in the first k positions is ranked at least as high as every remaining element. Because the keys are distinct and exactly k are returned, the answer is correct.
Complexity#
Expected O(n + u log u) time and O(u) auxiliary space plus O(k) result references. The bound includes the count map and sort storage. This implementation sorts all distinct values even if k = 0, which is unnecessary work but still correct. Sorting is a useful baseline and often a practical choice for small datasets or when k is close to u.
4. Approach B: bounded min-heap#
A min-heap exposes its smallest entry at the root. Rather than storing all values in a heap, keep at most k candidates. Define each candidate's priority as (frequency, negative first-occurrence order). Higher priority is better.
The negative order is important: an earlier value has a larger negative-order score, such as 0 compared with -3. The priority is unique for distinct values because the enumeration order is unique. The value is included as the third tuple field for returning the result.
PYTHONfrom collections import Counter from heapq import heappush, heapreplace def topk_heap(nums, k): counts = Counter(nums) if not 0 <= k <= len(counts): raise ValueError('k outside distinct-value count') if k == 0: return [] heap = [] for order, (value, freq) in enumerate(counts.items()): entry = (freq, -order, value) if len(heap) < k: heappush(heap, entry) elif entry > heap[0]: heapreplace(heap, entry) return [entry[2] for entry in sorted(heap, reverse=True)]
The final sort ensures the specified output order. If any output order is acceptable, returning the retained values directly from the heap avoids that final sort. A heap is only partially ordered; its underlying array is not a sorted list.
Dry run with replacements#
Take nums = [7,9,4,4,2,2,2,9] and k = 2.
| Candidate | Frequency | First-occurrence rank | Retained values after decision |
|---|---|---|---|
| 7 | 1 | 0 | 7 |
| 9 | 2 | 1 | 7,9 |
| 4 | 2 | 2 | 4,9; replace 7 |
| 2 | 3 | 3 | 9,2; replace 4 |
At the final step, 4 is the weakest retained candidate because 4 and 9 have equal counts but 4 appeared later. The returned ranked output is [2,9]. The table shows retained membership, not the literal heap array.
The diagram depicts the selection loop for valid k greater than zero. The implementation handles k = 0 before entering it.
Correctness proof using an invariant#
After processing j distinct values, the heap contains the best min(k, j) candidates from those j values under the declared total order.
Initially, no candidates have been processed, so the empty heap satisfies the invariant. If the heap is not full, adding the next candidate retains every candidate seen so far. If the heap is full, its root is the weakest retained candidate. A new candidate that does not outrank the root cannot belong to the top k of the enlarged prefix. A candidate that outranks the root belongs to the top k and replaces exactly the weakest previous candidate.
Induction establishes that the heap contains the correct top k after all u values have been processed. Sorting only those retained entries produces the required order without changing membership.
Complexity#
Counting takes expected O(n). Heap pushes and replacements cost O(log(k + 1)); examining the root takes O(1). Selection costs O(u log(k + 1)) in the worst case for heap operations. Sorting the retained k candidates costs O(k log(k + 1)). Since k ≤ u, expected total time is O(n + u log(k + 1)) for k ≥ 1, with the usual hashing assumptions.
The count map takes O(u) memory and the heap O(k); auxiliary space is O(u + k), excluding or including constant-factor result storage as specified. The selection structure is O(k), but the entire exact algorithm is not O(k) space because it retains all distinct counts.
5. Approach C: frequency buckets#
The input has n elements, so no value can occur more than n times. Create n + 1 buckets, where bucket f contains the values whose frequency is exactly f. Insert each distinct value in first-occurrence order, then scan from the largest frequency down.
PYTHONfrom collections import Counter def topk_bucket(nums, k): counts = Counter(nums) if not 0 <= k <= len(counts): raise ValueError('k outside distinct-value count') if k == 0: return [] buckets = [[] for _ in range(len(nums) + 1)] for value, freq in counts.items(): buckets[freq].append(value) result = [] for freq in range(len(nums), 0, -1): for value in buckets[freq]: result.append(value) if len(result) == k: return result return result
Dry run#
For nums = [1,1,1,2,2,3] and k = 2, n = 6.
| Frequency index | Contents |
|---|---|
| 6,5,4 | Empty |
| 3 | [1] |
| 2 | [2] |
| 1 | [3] |
| 0 | Empty; unused |
Visit bucket 3 and append 1. Visit bucket 2 and append 2. The result now contains k elements, so stop. If a bucket contains several equally frequent values, the code takes them in first-occurrence order and stops exactly at k rather than returning the entire bucket.
Correctness#
Each distinct value is assigned to exactly one bucket determined by its true frequency. Descending traversal ensures every higher-frequency value is considered before any lower-frequency value. Within a bucket, insertion order implements the tie rule. Therefore the traversal enumerates the complete ranking, and stopping after k values returns exactly the required prefix.
Complexity#
Creating n + 1 empty lists costs O(n) time and space, counting costs expected O(n), and filling buckets costs O(u). Scanning the frequency indices costs at most O(n), and extracting candidates costs at most O(u). Because u ≤ n for a nonempty array, expected total time is O(n) and auxiliary space is O(n).
One refinement is to allocate only max_frequency + 1 buckets, which may save memory for data with many unique values. It is especially useful when the maximum observed frequency is much smaller than n. The shown implementation uses n + 1 buckets for clarity.
Use a list comprehension for independent buckets. Writing buckets = [[]] * (n + 1) would make every bucket reference the same list.
6. Compare the algorithms#
| Approach | Expected time including counting | Auxiliary space | When I would choose it |
|---|---|---|---|
| Sort distinct values | O(n + u log u) | O(u) | Simplicity, small u, k near u |
| Size-k min-heap | O(n + u log(k + 1)) | O(u + k) | k small relative to u; bounded selection structure |
| Frequency buckets | O(n) | O(n) | Finite list, memory available, exact linear-time selection |
The bounds assume expected constant-time hash-map operations for ordinary inputs and unit-cost integer operations. Pathological hash collisions can degrade the counting stage. The heap comparisons also assume constant-size priorities. Python integers are arbitrary precision, so extremely large values have additional hashing and arithmetic costs.
Bucket selection is asymptotically optimal in expected time for arbitrary finite input because exact frequency ranking can depend on the last unseen element; the algorithm may need to read the entire list. This does not make it automatically faster than a heap in practice. The allocation of many Python list objects can be expensive. Benchmark realistic n, u, k and frequency skew.
Quickselect is another possible selection method after counting. With appropriate pivot selection and a total-order priority, it can find the top-k boundary in expected O(u) time, although basic quickselect has O(u²) worst-case time. Returning the top k in ranked order requires additional sorting unless the selection method already provides that order. A full quickselect implementation is not required for this question.
7. Edge cases and mistakes#
- k = 0: return no values; do not read an empty heap root.
- Empty input: only k = 0 is valid under the extended contract.
- k = u: return every distinct value in ranked order.
- All values equal: there is one distinct candidate, not n candidates.
- All values have equal frequency: the tie policy determines selection and order.
- Negative or large integer values: bucket indices are frequencies, not the values themselves.
- Invalid k: reject according to the declared API contract rather than silently return fewer values.
- Ties at the kth boundary: avoid returning all tied values when exactly k are requested.
- Heap replacement: compare with the weakest retained candidate, not the strongest.
- Counting and selection: do not count each value again with nums.count inside the production selection loop; repeated full scans can be quadratic.
8. Local implementation verification#
All three exact Python functions above were executed using Python 3.13.5.
The independent oracle built the distinct values in first-occurrence order and repeatedly selected the remaining value with greatest frequency using direct list counting. Stable first-occurrence ordering resolved ties. This deliberately slower reference does not depend on the tested heap or bucket implementation.
- 96,105 exhaustive input/k combinations across all arrays of length zero through seven over {-1,0,1,2}, testing every valid k.
- 5,183 additional input/k combinations from 200 seeded randomized arrays, testing every valid k for each generated array.
- Four regression combinations using integers of magnitude 10^100.
- Nine invalid-k checks across the three functions.
Each implementation passed all 101,292 valid cases, yielding 303,876 validated results, plus nine invalid-input checks: 303,885 total checks passed. The standard sample also returned [1,2] for each implementation. Tests verified exact ranked equality to the independent oracle, including tie boundaries and zero k.
These are synthetic correctness checks, not performance benchmarks or distributed-system tests.
9. Production and FDE considerations#
Top-k frequency selection appears in common error-code analysis, product analytics, endpoint traffic summaries and support issue categorization. In a real system, first agree on what constitutes an event, the observation window, the grouping key and how retries or duplicate deliveries are counted.
A streaming dashboard for the most frequent API errors over the last hour is not simply a top-k computation over an unbounded lifetime stream. It needs an event-time policy, window expiration, late-event handling and appropriate aggregation. Exact lifetime counts require state proportional to the distinct-value cardinality; an exact sliding window may additionally require expiration state.
For high-cardinality streams with constrained memory, approximate heavy-hitter methods such as Space-Saving or a Count-Min Sketch with candidate tracking can be appropriate. They have different guarantees from exact top-k. A Count-Min Sketch by itself estimates frequencies of queried keys; it does not enumerate the top keys without a separate candidate mechanism. Explain error bounds, window behavior and the possibility of misranking near the cutoff. Validate estimates against an exact sample.
For distributed exact counting, aggregate per-key counts across partitions before final ranking. Simply merging local top-k lists can miss a globally frequent element. For example, with k = 1, shard A has a:6 and x:5 while shard B has b:6 and x:5. Local winners are a and b, but globally x has ten occurrences and should rank first. Partitioning by value and then selecting across disjoint fully aggregated key sets is a different architecture in which local top-k candidates can suffice for a global top-k under a consistent total order.
Keep tenant scope, time windows and access control explicit in customer-facing analytics. Do not publish another customer's sensitive high-frequency identifiers merely because global aggregation makes them available.
Likely interviewer follow-ups#
Why use a min-heap rather than a max-heap? A size-k min-heap exposes the weakest retained candidate for replacement. A max-heap over all u values is another valid approach, but it stores all u candidates. Building such a heap and extracting k maxima has different cost and memory characteristics.
Why not just use Counter.most_common(k)? It is a convenient Python API and may be perfectly suitable in production. In an algorithm interview, show that you understand counting, selection, complexity and tie handling rather than relying solely on a convenience method. Check the library's documented behavior when deterministic ties matter.
What if the interviewer says better than O(n log n) is mandatory? The frequency-bucket approach is expected O(n) with O(n) space. A small-k heap can also improve the selection cost relative to sorting all values, but does not guarantee linear time for all k.
What if output order is irrelevant? The heap does not need its final sort, and any valid tied candidates can be accepted if the problem permits arbitrary ties. Preserve exactly k distinct values.
What if the data never fits in memory? Consider external aggregation, a distributed count-by-key pipeline, or a bounded-memory approximate method if the product permits errors. A small final heap alone does not solve the memory requirement of exact counts.
How is this different from kth-largest element? Top-k frequency ranks distinct values by occurrence count, not by numeric magnitude. Counting is therefore a necessary part of the problem.
Interview takeaway#
Count once, then select intelligently. Sorting is the straightforward baseline, a bounded min-heap is useful when k is small, and frequency buckets exploit the bounded integer range of counts to achieve expected linear time. Be explicit about ties, distinctness, exact output size, and the difference between heap space and the count-map memory.
References
- 1.
- 2.Python documentation — heapq (not live-verified)docs.python.org
- 3.Python documentation — Sorting HOW TO (not live-verified)docs.python.org
- 4.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models