K-Way Merge

Merge k sorted lists, or pick items by rank across them, with a min-heap that holds one candidate per list. N items cost O(N log k).

Overview

The idea

Merge sort merges two sorted lists by looking at their two front items and taking the smaller one. K-way merge does the same with k lists. At every step the next output item is the smallest of the k front items. A min-heap that holds exactly those k items finds it in O(log k), and the heap never grows past k.

Picture the front item of list 1, the front item of list 2 and so on up to list k, each feeding one entry into a min-heap of k items. You pop the smallest entry into the sorted output, then push the next item from the same list to take its place. The heap holds only the front item of each list, so it stays at size k while the lists can be any length.

Each heap entry must remember where it came from, so the next item can be pulled from the same list. In Python the entry is a tuple (value, list index, position). Tuples compare item by item, so equal values are broken by list index and two positions are never compared to each other.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio