Counting, then choosing the top
After this: Find the k most frequent values with a hash map and a small heap, and read the table of all ten.
On this page · 4 sections · 3 checks
A shop wants to know its two best-selling items from a list of sales. That takes two steps: count how often each item was sold, then choose the biggest counts. The last problem in this tutorial puts two tools together for those two steps, the way the last lesson of Which tool for which problem did.
10. Top k frequent elements
Pattern: count with a hash map, then keep the k biggest counts in a min-heap. The map turns the list into counts in one pass. Then a of size k keeps the biggest counts: push each count, and whenever the heap holds one too many, pop the smallest. What is left is the k biggest.
Work through [4, 1, 4, 2, 1, 4, 3] with k = 2:
- Count: 4 appears 3 times, 1 twice, 2 once and 3 once.
- Push the count 3 (for 4), then 2 (for 1). The heap holds two counts.
- Push 1 (for 2). Now there are three, so pop the smallest, 1.
- Push 1 (for 3), and pop the smallest again.
- The heap holds the counts 2 and 3. They belong to 1 and 4, so the answer, biggest first, is
[4, 1].
The task below does steps 2 to 4 on the counts alone.
- Push 3Push 3, the count of the value 4.
- Push 2
- Push 1
- Pop the minimum
- Push 1
- Pop the minimum
- 0
empty
Push a few values and watch them sift up.
Now the whole function, with the values carried along:
- Run the programRun it and step through. First watch counts fill up. Then watch heap: whenever it holds three entries, the one with the smallest count is taken out.
import heapq
def top_k_frequent(nums, k): counts = {} for x in nums: counts[x] = counts.get(x, 0) + 1 heap = [] # (count, value), smallest count on top for value, count in counts.items(): heapq.heappush(heap, (count, value)) if len(heap) > k: heapq.heappop(heap) return [pair[1] for pair in sorted(heap, reverse=True)]
print(top_k_frequent([4, 1, 4, 2, 1, 4, 3], 2))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
In Python, heapq compares tuples, so the heap holds (count, value) pairs and the count decides. The last line sorts the pairs, biggest count first, and keeps the value from each pair.In Java, the heap holds the values, and its comparator orders them by their counts in the map. The map is a LinkedHashMap, which keeps the order in which values were first seen, as Python's dict does. The last lines copy the heap into a list and sort it, biggest count first. With [5] and k = 1, the answer is [5].
Cost. Counting is O(n) for n numbers. Then each of the m different values is pushed into a heap that never holds more than k + 1, so each push or pop costs about log k: O(m log k). In all, at most O(n log k). Sorting all the counts instead costs O(m log m), which is also a correct answer; say which one you chose and why. Extra memory: O(m) for the map and O(k) for the heap.
Run it
All ten in one table
| Problem | Pattern | Time | Extra memory | Pinned example |
|---|---|---|---|---|
| Two sum | hash map | O(n) | O(n) | [3, 2, 4], target 6 → [1, 2] |
| Binary search | binary search | O(log n) | O(1) | target 23 in the ten-number row → 5 |
| Best day to buy and sell | one pass, lowest price so far | O(n) | O(1) | [8, 3, 6, 1, 4, 7, 2] → 6 |
| Valid parentheses | stack | O(n) | O(n) | "{[()]}" → valid, "([)]" → not |
| Longest stretch with no repeat | sliding window and a map | O(n) | grows with the different characters | "streets" → 4 |
| Reverse a linked list | three pointers | O(n) | O(1) | 1 → 2 → 3 → 4 becomes 4 → 3 → 2 → 1 |
| Merge two sorted lists | two pointers and a dummy node | O(n + m) | O(1) | [1, 4, 6] + [2, 3, 7, 8] → [1, 2, 3, 4, 6, 7, 8] |
| Maximum depth | recursion | O(n) | grows with the height | the example tree → 4 |
| Number of islands | depth-first search from each new land cell | O(rows × cols) | O(rows × cols) | 110 / 010 / 001 → 2 |
| Top k frequent | hash map, then a min-heap of size k | O(n log k) at most | O(m + k) | [4, 1, 4, 2, 1, 4, 3], k = 2 → [4, 1] |
Check yourself
Return the k values that appear most often in a list. Which two tools does the solution use, in order?
The counting loop has read all seven numbers of [4, 1, 4, 2, 1, 4, 3]. What does the map hold? Each chip is value: count.
The list has n numbers, m of them different, and you want the top k. What is the cost of the map-then-heap solution, in words?
- Find the k most frequent values: count with a hash map, then keep the k biggest counts in a min-heap of size k.
- State the cost as O(n) to count plus O(m log k) for the heap, and name sorting all the counts, O(m log m), as an accepted choice.
- Say why the two languages may differ on ties: Python compares (count, value) pairs, Java's comparator only the counts.
- Read the table of all ten problems: the pattern, time, extra memory and a pinned example for each.