Heaps · Pattern 3 of 4

Merge k sorted lists and arrays

Put the first item of every sorted source in a min heap. Pop the smallest, output it, and push the next item from the same source. N items from k sources cost O(N log k).

3 variations · 4 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

  • k sorted lists, arrays, files or feeds to combine into one sorted output
  • The smallest range, or the next best item, across several sorted sources
  • The most recent items from many users, each user's items already in time order

The template

Merge K Sorted
// heap entries: {value, which list, index in that list}
int[] mergeKSorted(int[][] lists) {
    PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    int total = 0;
    for (int r = 0; r < lists.length; r++) {
        total += lists[r].length;
        if (lists[r].length > 0) heap.offer(new int[]{lists[r][0], r, 0});
    }
    int[] res = new int[total];
    for (int i = 0; !heap.isEmpty(); i++) {
        int[] top = heap.poll();
        res[i] = top[0];
        int r = top[1], c = top[2] + 1;
        if (c < lists[r].length) heap.offer(new int[]{lists[r][c], r, c});   // the next from that list
    }
    return res;
}

// smallest range with one number from every list: pop the min, track the max
int[] smallestRange(int[][] lists) {
    PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
    int hi = Integer.MIN_VALUE;
    for (int r = 0; r < lists.length; r++) {
        heap.offer(new int[]{lists[r][0], r, 0});
        hi = Math.max(hi, lists[r][0]);
    }
    int[] best = {heap.peek()[0], hi};
    while (true) {
        int[] top = heap.poll();
        if (hi - top[0] < best[1] - best[0]) best = new int[]{top[0], hi};
        int r = top[1], c = top[2] + 1;
        if (c == lists[r].length) return best;            // a list ran out
        heap.offer(new int[]{lists[r][c], r, c});
        hi = Math.max(hi, lists[r][c]);
    }
}

The variations

  1. 1Merge k sorted sources

    The heap holds one candidate per source: the value plus where it came from. Pop, output, push that source's next item. With linked lists the node itself knows its next, so store the node.

  2. 2Pop the min, track the max

    Keep exactly one number from every list. The heap gives the minimum, and a plain variable remembers the maximum. Moving the minimum forward is the only way the range can shrink; stop when any list runs out.

  3. 3Merging inside a design

    A news feed is a merge of each followed user's posts, newest first. Push each user's latest post, pop the newest, push that user's previous post, and stop after 10.

    Worked example Design Twitter Medium Read the solution

Mistakes to avoid

  • Pushing every item of every list at the start: it works, but costs O(N log N) instead of O(N log k).
  • Forgetting to push the next item from the same source after a pop, so a list stops after its first item.
  • Pushing empty lists (or null list heads) into the heap.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.