AlgoTales · Roadmap

Merge K sorted arrays/lists

Advanced · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Merging k sorted lists means producing one sorted list from several that are each already in order. A heap holding the front item of every list always tells you which one to take next, so you never re-sort the whole thing.

Practical use cases

  • Web app: Merging logs from many servers. A site runs on 8 servers, and each writes a log sorted by time. The support team wants one combined log in time order. A heap holding the next line from each server gives the earliest line, and the combined log streams out without loading all files.
  • Web app: Combined feed from several sources. A news app pulls sorted lists from 5 sources and shows them as one feed, newest first. Each source offers its next article to a heap, and the newest is shown. The page gets its first screen after only a few steps instead of waiting for everything.
  • System: External sorting and database storage. When data is too big for memory, it is sorted in chunks and then merged using this method. Search engine indexes and storage engines such as LSM trees merge many sorted files in the background the same way. Users never notice, but it keeps reads fast.

The story: Three Counters, One Line

At a busy railway station, three ticket counters A, B and C each served tokens in increasing order: A had 1, 5, 9; B had 2, 3, 8; C had 4, 6, 7. The station master wanted one single list of tokens in order, for the display board.

The obvious way: dump all tokens into one pile and sort it. But the tokens were already sorted within each counter. Why waste that? Mira said, "The smallest token overall must be the front of one of the counters. We only ever need to look at three fronts."

She kept a min heap holding just the three fronts: 1, 2, 4. The top, 1, was the winner, so it went to the merged line. Then counter A's next token, 5, stepped into the heap. Again the top (2) won. Counter B's next, 3, stepped in. They repeated until all counters were empty, and the merged line came out perfectly sorted.

That is merging K sorted arrays (or linked lists). The heap size stays K, no matter how many tokens there are, so it costs about log K per token instead of sorting the whole pile.

How to spot this problem, and where you need it

You have several lists that are each already sorted and need one combined sorted result, without concatenating and sorting everything again.

Signs you need it

  • Data comes from many shards, servers, files or API sources, each returning sorted results.
  • Your code joins all results into one array and calls sort(), and it gets slow or runs out of memory as the sources grow.
  • The task says "merge k sorted lists" or "combine sorted streams".

Where to use it in a project

  • Combining sorted results from multiple database shards, APIs or log files into one page or file.
  • Large sorting jobs that sort pieces on disk and merge them.

The solution

Put the first item of each list in a min heap, remembering which list it came from. Take the smallest from the heap and add it to the output. Then push the next item from the same list into the heap. Repeat until the heap is empty. The heap size never exceeds k, the number of lists.

Payoff: Before: concatenate and sort 8 million log lines in memory. After: stream the merge with a heap of only 8 items.

Explain it like I am 8

Three lines of kids are each standing in height order. To make one big line, look at the first kid of each line, pick the shortest of these three, and move that kid to the new line. Then look at the new first kids and pick again. You only ever compare the front kids!

How it works, step by step

  1. Put the first item of each of the K lists in a min heap, remembering which list and position it came from.
  2. Pop the smallest item and append it to the answer.
  3. Take the next item from the same list (if any) and push it into the heap.
  4. Repeat until the heap is empty. Every item has been output exactly once.
  5. For linked lists, store the node itself and move to node.next instead of an index.

The code in four languages

PHP

<?php
// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before($x, $y) answers: "does x belong closer to the top than y?"  (default = min-heap)
class Heap {
    private array $a = [];
    private $before;
    public function __construct(?callable $before = null) {
        $this->before = $before ?? fn($x, $y) => $x < $y;
    }
    public function size(): int { return count($this->a); }
    public function peek() { return $this->a[0] ?? null; }
    public function push($v): void {             // put it at the bottom, then climb
        $this->a[] = $v;
        $i = count($this->a) - 1;
        while ($i > 0) {
            $p = intdiv($i - 1, 2);
            if (!($this->before)($this->a[$i], $this->a[$p])) break;
            [$this->a[$i], $this->a[$p]] = [$this->a[$p], $this->a[$i]];
            $i = $p;
        }
    }
    public function pop() {                      // take the top, put the last one on top, sink it
        if (count($this->a) === 0) return null;
        $top = $this->a[0];
        $last = array_pop($this->a);
        $n = count($this->a);
        if ($n > 0) {
            $this->a[0] = $last;
            $i = 0;
            while (true) {
                $l = 2 * $i + 1; $r = $l + 1; $best = $i;
                if ($l < $n && ($this->before)($this->a[$l], $this->a[$best])) $best = $l;
                if ($r < $n && ($this->before)($this->a[$r], $this->a[$best])) $best = $r;
                if ($best === $i) break;
                [$this->a[$i], $this->a[$best]] = [$this->a[$best], $this->a[$i]];
                $i = $best;
            }
        }
        return $top;
    }
}

// Merge K sorted arrays. Each heap entry is [value, which list, position in that list].
function mergeK(array $lists): array {
    $heap = new Heap(fn($x, $y) => $x[0] < $y[0]);
    foreach ($lists as $li => $list) {
        if (count($list) > 0) $heap->push([$list[0], $li, 0]);       // the front of each list
    }
    $merged = [];
    while ($heap->size() > 0) {
        [$value, $li, $pos] = $heap->pop();                          // the smallest front
        $merged[] = $value;
        if ($pos + 1 < count($lists[$li])) {                         // that list has a next item
            $heap->push([$lists[$li][$pos + 1], $li, $pos + 1]);
        }
    }
    return $merged;
}

echo implode(' ', mergeK([[1, 5, 9], [2, 3, 8], [4, 6, 7]])), PHP_EOL;   // 1 2 3 4 5 6 7 8 9
echo implode(' ', mergeK([[], [5], [1, 2]])), PHP_EOL;                    // 1 2 5 (empty lists are fine)

JavaScript

// A heap lives in a plain array. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"  (default = min-heap)
class Heap {
  constructor(before = (x, y) => x < y) { this.a = []; this.before = before; }
  size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(v) {                          // put it at the bottom, then climb
    const a = this.a; a.push(v);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.before(a[i], a[p])) break;
      [a[i], a[p]] = [a[p], a[i]]; i = p;
    }
  }
  pop() {                            // take the top, put the last one on top, sink it
    const a = this.a;
    if (a.length === 0) return null;
    const top = a[0], last = a.pop();
    if (a.length > 0) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1; let best = i;
        if (l < a.length && this.before(a[l], a[best])) best = l;
        if (r < a.length && this.before(a[r], a[best])) best = r;
        if (best === i) break;
        [a[i], a[best]] = [a[best], a[i]]; i = best;
      }
    }
    return top;
  }
}

// Merge K sorted arrays. Each heap entry is [value, which list, position in that list].
function mergeK(lists) {
  const heap = new Heap((x, y) => x[0] < y[0]);
  lists.forEach((list, li) => {
    if (list.length > 0) heap.push([list[0], li, 0]);              // the front of each list
  });
  const merged = [];
  while (heap.size() > 0) {
    const [value, li, pos] = heap.pop();                           // the smallest front
    merged.push(value);
    if (pos + 1 < lists[li].length) {                              // that list has a next item
      heap.push([lists[li][pos + 1], li, pos + 1]);
    }
  }
  return merged;
}

console.log(mergeK([[1, 5, 9], [2, 3, 8], [4, 6, 7]]).join(' '));  // 1 2 3 4 5 6 7 8 9
console.log(mergeK([[], [5], [1, 2]]).join(' '));                   // 1 2 5 (empty lists are fine)

Java

import java.util.*;
import java.util.function.BiPredicate;

public class Main {
    // A heap lives in a plain list. Spot i has children at 2*i+1 and 2*i+2.
    // before(x, y) answers: "does x belong closer to the top than y?"
    static class Heap<T> {
        private final List<T> a = new ArrayList<>();
        private final BiPredicate<T, T> before;

        Heap(BiPredicate<T, T> before) { this.before = before; }

        int size() { return a.size(); }

        void push(T v) {                          // put it at the bottom, then climb
            a.add(v);
            int i = a.size() - 1;
            while (i > 0) {
                int p = (i - 1) / 2;
                if (!before.test(a.get(i), a.get(p))) break;
                Collections.swap(a, i, p);
                i = p;
            }
        }

        T pop() {                                 // take the top, put the last one on top, sink it
            if (a.isEmpty()) return null;
            T top = a.get(0);
            T last = a.remove(a.size() - 1);
            int n = a.size();
            if (n > 0) {
                a.set(0, last);
                int i = 0;
                while (true) {
                    int l = 2 * i + 1, r = l + 1, best = i;
                    if (l < n && before.test(a.get(l), a.get(best))) best = l;
                    if (r < n && before.test(a.get(r), a.get(best))) best = r;
                    if (best == i) break;
                    Collections.swap(a, i, best);
                    i = best;
                }
            }
            return top;
        }
    }

    // Each heap entry is [value, which list, position in that list].
    record Entry(int value, int list, int pos) {}

    // Merge K sorted arrays.
    static List<Integer> mergeK(int[][] lists) {
        Heap<Entry> heap = new Heap<>((x, y) -> x.value() < y.value());
        for (int li = 0; li < lists.length; li++) {
            if (lists[li].length > 0) heap.push(new Entry(lists[li][0], li, 0));   // the front of each list
        }
        List<Integer> merged = new ArrayList<>();
        while (heap.size() > 0) {
            Entry e = heap.pop();                                    // the smallest front
            merged.add(e.value());
            if (e.pos() + 1 < lists[e.list()].length) {              // that list has a next item
                heap.push(new Entry(lists[e.list()][e.pos() + 1], e.list(), e.pos() + 1));
            }
        }
        return merged;
    }

    public static void main(String[] args) {
        System.out.println(mergeK(new int[][]{{1, 5, 9}, {2, 3, 8}, {4, 6, 7}}));   // [1, 2, 3, 4, 5, 6, 7, 8, 9]
        System.out.println(mergeK(new int[][]{{}, {5}, {1, 2}}));                    // [1, 2, 5] (empty lists are fine)
    }
}

Go

package main

import "fmt"

// A heap lives in a plain slice. Spot i has children at 2*i+1 and 2*i+2.
// before(x, y) answers: "does x belong closer to the top than y?"
type Heap[T any] struct {
	a      []T
	before func(x, y T) bool
}

func (h *Heap[T]) Size() int { return len(h.a) }

// Push puts it at the bottom, then climbs.
func (h *Heap[T]) Push(v T) {
	h.a = append(h.a, v)
	i := len(h.a) - 1
	for i > 0 {
		p := (i - 1) / 2
		if !h.before(h.a[i], h.a[p]) {
			break
		}
		h.a[i], h.a[p] = h.a[p], h.a[i]
		i = p
	}
}

// Pop takes the top, puts the last one on top, and sinks it.
func (h *Heap[T]) Pop() (T, bool) {
	var zero T
	if len(h.a) == 0 {
		return zero, false
	}
	top := h.a[0]
	last := h.a[len(h.a)-1]
	h.a = h.a[:len(h.a)-1]
	n := len(h.a)
	if n > 0 {
		h.a[0] = last
		i := 0
		for {
			l, r, best := 2*i+1, 2*i+2, i
			if l < n && h.before(h.a[l], h.a[best]) {
				best = l
			}
			if r < n && h.before(h.a[r], h.a[best]) {
				best = r
			}
			if best == i {
				break
			}
			h.a[i], h.a[best] = h.a[best], h.a[i]
			i = best
		}
	}
	return top, true
}

// Each heap entry is {value, which list, position in that list}.
type entry struct{ value, list, pos int }

// mergeK merges K sorted slices.
func mergeK(lists [][]int) []int {
	heap := &Heap[entry]{before: func(x, y entry) bool { return x.value < y.value }}
	for li, list := range lists {
		if len(list) > 0 {
			heap.Push(entry{list[0], li, 0}) // the front of each list
		}
	}
	var merged []int
	for heap.Size() > 0 {
		e, _ := heap.Pop() // the smallest front
		merged = append(merged, e.value)
		if e.pos+1 < len(lists[e.list]) { // that list has a next item
			heap.Push(entry{lists[e.list][e.pos+1], e.list, e.pos + 1})
		}
	}
	return merged
}

func main() {
	fmt.Println(mergeK([][]int{{1, 5, 9}, {2, 3, 8}, {4, 6, 7}})) // [1 2 3 4 5 6 7 8 9]
	fmt.Println(mergeK([][]int{{}, {5}, {1, 2}}))                 // [1 2 5] (empty lists are fine)
}

Time: O(N log K) · Extra space: O(K). N is the total number of items. Each is pushed and popped once, in a heap that holds at most K entries (one per list).

Watch out for

  • Dumping everything into one array and sorting it. It works but ignores the fact that each list is already sorted.
  • Forgetting to remember which list a popped value came from, so you do not know where to fetch the next item.
  • Not handling empty lists. Only push the first item of a list if it has one.

Quick check

  1. What does the heap contain while merging K lists?
    • One front item from each list (at most K)
    • Only the smallest item
    • All the items
  2. After popping a value, what is pushed?
    • Nothing
    • The next item from the same list
    • The largest item
  3. Total time to merge K lists with N items in total?
    • O(N log K)
    • O(N²)
    • O(K²)