Heaps · Pattern 2 of 4
Custom comparators: ordering by several keys
The heap is only as good as its comparator. Compare the main key first and break ties with the next one, so "most frequent, then smallest value" or "highest priority, then highest id" comes out on top.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The answer must be ordered by one value and then by another on ties
- A design problem: "the task with the highest priority, and on a tie the largest id"
- Ranking by many positions, falling back to alphabetical order
The template
// k most frequent values, most frequent first; ties: the smaller value first
int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int x : nums) count.merge(x, 1, Integer::sum);
// the WORST candidate sits on top: fewer occurrences, then the larger value
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) ->
a[1] != b[1] ? Integer.compare(a[1], b[1]) : Integer.compare(b[0], a[0]));
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
heap.offer(new int[]{e.getKey(), e.getValue()});
if (heap.size() > k) heap.poll();
}
int[] res = new int[heap.size()];
for (int i = res.length - 1; i >= 0; i--) res[i] = heap.poll()[0]; // best ends up first
return res;
} import heapq
from collections import Counter
def top_k_frequent(nums, k): # most frequent first; ties: smaller value first
heap = []
for x, c in Counter(nums).items():
heapq.heappush(heap, (c, -x)) # the worst on top: fewer, then the larger value
if len(heap) > k:
heapq.heappop(heap)
res = []
while heap:
res.append(-heapq.heappop(heap)[1])
return res[::-1] # best first // k most frequent values, most frequent first; ties: the smaller value first
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> count;
for (int x : nums) count[x]++;
// (value, count); "a is better than b", so the worst candidate sits on top
auto better = [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second != b.second ? a.second > b.second : a.first < b.first;
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(better)> heap(better);
for (auto& [x, c] : count) {
heap.push({x, c});
if ((int)heap.size() > k) heap.pop();
}
vector<int> res;
for (; !heap.empty(); heap.pop()) res.push_back(heap.top().first);
reverse(res.begin(), res.end()); // best first
return res;
} // a binary heap; less(a, b) is true when a should come out first
class MinHeap {
constructor(less = (a, b) => a < b) { this.a = []; this.less = less; }
get size() { return this.a.length; }
peek() { return this.a[0]; }
push(x) {
const a = this.a; a.push(x);
for (let i = a.length - 1; i > 0;) { // sift up
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]]; i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length) {
a[0] = last;
for (let i = 0; ;) { // sift down
const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && this.less(a[l], a[m])) m = l;
if (r < a.length && this.less(a[r], a[m])) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]]; i = m;
}
}
return top;
}
}
// k most frequent values, most frequent first; ties: the smaller value first
function topKFrequent(nums, k) {
const count = new Map();
for (const x of nums) count.set(x, (count.get(x) || 0) + 1);
// [value, count]; the worst on top: fewer occurrences, then the larger value
const heap = new MinHeap((a, b) => a[1] < b[1] || (a[1] === b[1] && a[0] > b[0]));
for (const [x, c] of count) {
heap.push([x, c]);
if (heap.size > k) heap.pop();
}
const res = [];
while (heap.size) res.push(heap.pop()[0]);
return res.reverse(); // best first
} The variations
-
1Main key, then a tie-break
Store tuples and compare field by field: the count, then the value. For ranked votes the "key" is the whole row of position counts, compared position by position, then the team letter.
Now you solve- Rank Teams by Votes Medium Stuck? solution
- Single-Threaded CPU Medium Stuck? ▶ video
-
2Ordered entries inside a design
Keep the live state in hash maps and the ordering in a heap (or a sorted set) of tuples like (priority, id). Edits and removals push a new entry or mark the old one stale; when a stale entry reaches the top, check it against the map and pop it.
Now you solve
Mistakes to avoid
- Getting the tie-break backwards in a size-k heap: the top must be the item you would drop, so every key is flipped compared with the final order.
- In C++, the comparator says "a comes out after b":
priority_queueputs the greatest item on top, the opposite ofsort. - In a design problem, trying to edit an entry inside the heap. Push the new version and skip entries that no longer match the hash map.
Lesson done
Next: Merge k sorted lists and arrays →Mark it done once you can write the template from memory and you have solved the worked examples yourself.