AlgoFrames

Priority queues in practice: top-k, k-way merge, scheduling

Priority queues solve top-k, k-way merge and scheduling problems by always handing you the most urgent item next.

Before you start: Heap sort.

The idea

A priority queue hands you the most urgent item next. Here the outage comes out first, even if email arrived earlier.

A binary heap gives push and pop in O(log n). This lesson uses it as a tool: keep the best k values, merge sorted lists, plan a schedule.

Intuition

To keep the 2 largest of 5, 1, 9, 3, 7, hold the best 2 in a min-heap. Its top, 7, is the value a newcomer must beat.

A min-heap puts the weakest kept value on top. When a new value pushes the size past k, that weakest value leaves in one pop.

Complexity

Sorting all n values costs n log n. A heap that never passes k values costs n log k, and k is often tiny.

Top 10 of a million values: each value costs about 3 heap steps instead of 20, and memory holds 10 values. Merging k lists costs n log k for the same reason.

Pitfalls

For the k largest, use a min-heap. A max-heap puts 9 on top, so a pop throws away the best value.

Pops come out smallest first: 7, then 9. Write them from the last slot back, or reverse the list at the end.

Variations

Top k frequent: count values in a hash map, then keep the k highest counts in a size-k min-heap.

Scheduling: a max-heap picks the task with most copies left. A task that just ran waits in the cooldown queue; D@2 means D is ready at time 2.

Code

Pseudocode

kLargest(values, k)
  heap ← empty min-heap
  for x in values
    push x into heap
    if size(heap) > k
      pop the smallest from heap
  result ← array of size(heap)
  for j from size(heap) - 1 down to 0
    result[j] ← pop the smallest from heap
  return result

Python

import heapq

def k_largest(values, k):
    heap = []
    for x in values:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)
    result = [0] * len(heap)
    for j in range(len(heap) - 1, -1, -1):
        result[j] = heapq.heappop(heap)
    return result

JavaScript

function kLargest(values, k) {
  const heap = new MinHeap();
  for (const x of values) {
    heap.push(x);
    if (heap.size() > k) {
      heap.pop();
    }
  }
  const result = new Array(heap.size());
  for (let j = heap.size() - 1; j >= 0; j--) {
    result[j] = heap.pop();
  }
  return result;
}

Java

static int[] kLargest(int[] values, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>();
    for (int x : values) {
        heap.add(x);
        if (heap.size() > k) {
            heap.poll();
        }
    }
    int[] result = new int[heap.size()];
    for (int j = heap.size() - 1; j >= 0; j--) {
        result[j] = heap.poll();
    }
    return result;
}

Practice problems (7)

Which heap keeps the top k? Warm-up

You stream one million numbers and must keep the 10 largest seen so far, using as little memory as possible. Which heap do you keep?

K largest values Warm-up

Given an array nums and a whole number k, return the k largest values of nums, largest first. Equal values count separately, so [4, 4, 1] with k = 2 gives [4, 4].

Use a min-heap that never holds more than k values. Do not sort the whole array.

Last stone weight Warm-up

Each value in stones is the weight of a stone. Each turn, take the two heaviest stones, y ≥ x. If they weigh the same, both are destroyed. Otherwise x is destroyed and y becomes y - x.

Repeat until at most one stone is left. Return its weight, or 0 when no stone is left.

Merge k sorted lists Standard

lists holds k lists, and each one is sorted from smallest to largest. Merge them into one sorted list and return it.

Aim for O(n log k) time, where n is the total number of values: keep only the front value of each list in a min-heap.

Top k frequent values Standard

Return the k values that appear most often in nums. Order them by count, highest first. When two values have the same count, the smaller value comes first.

Count with a hash map, then keep a min-heap of at most k (count, value) pairs.

Trace a size-k min-heap Standard

Keep the 3 largest values of [4, 9, 2, 7, 5, 8] with a min-heap of size 3. Answer each question before the step plays.

Task scheduler Challenge

A CPU runs one task per time unit. tasks lists the tasks by letter, and the same letter can appear many times. Two runs of the same letter need at least n other time units between them. A time unit can be idle.

Return the fewest time units needed to run every task. Greedy works: at each time unit, run the ready task with the most copies left.

Related topics

Next on the path: Tries: insert, search, prefix