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.

2 variations · 5 problems · 2 with animated walkthroughs

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

Composite comparator
// 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;
}

The variations

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

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

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_queue puts the greatest item on top, the opposite of sort.
  • 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.
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.