Skip to content

visual walkthrough

Merge k Sorted Lists

HardK-way Merge (Heap / Divide & Conquer)Reported at: MetaAmazonMicrosoft+9

Heap-based or divide-and-conquer merging; a classic Hard.

Solve on LeetCode

The idea

With two lists you compare two fronts. With k lists you need the smallest of k fronts at every step, which a min-heap gives in O(log k).

Merging lists into the result one by one also works, but nodes merged early get walked again with every later list.

Complexity

approachtimespace
Merge one at a timeO(k × N)O(1)
Min-heap of frontsO(N log k)O(k)

More walkthroughs