Blind 75 · Linked List

Merge K Sorted Lists

Hard

Watch the walkthrough (5:39)

Problem

The input is lists, an array of k linked lists.
Each list is sorted, smallest value first.
Merge them all into a single sorted list, made of their own nodes.
Return the head of the merged list.
The array may be empty, and any list in it may be empty.
In the tests, lists is written [[1,4,5],[1,3,4],[2,6]].

Examples

Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]

Example 2:
Input: lists = []
Output: []

Example 3:
Input: lists = [[]]
Output: []

Example 4:
Input: lists = [[7]]
Output: [7]

Constraints

0 <= k <= 10^4
0 <= each list's length <= 500
0 <= the total number of nodes <= 10^4
-10^4 <= Node.val <= 10^4
Every list is sorted ascending.

Prerequisites

Linked lists — a node holds a value and a next reference, and rearranging a list means moving references, never values.
Dummy heads: a node in front of the list so the first element stops being a special case.
Two pointers on a list — one ahead of the other, or one moving twice as fast.

How to think about it

1. Min-Heap of the Fronts Optimal

Intuition

The next node of the answer is the smallest front among the k lists — and "smallest of k, repeatedly" is what a heap is for. Every node enters and leaves the heap once, so the cost is one log-k comparison per node rather than a scan of all k. Merging the lists one at a time re-walks the accumulated result each round, which is the O(N*k) answer this replaces.

Algorithm

1. Push the head of every non-empty list into a min-heap keyed on value.
2. Pop the smallest, attach it to the tail of the answer.
3. Push that node's successor, if any.
4. Repeat until the heap empties.

Time & Space

Time O(N log k) for N nodes across k lists. Space O(k) for the heap. Divide-and-conquer pairwise merging reaches the same bound.

2. Divide and Conquer, in Pairs

Intuition

Two sorted lists merge into one in a single walk, with a dummy and a tail. So merge the lists two at a time: k lists become k/2, then k/4, until one is left. Each round walks each node at most once, and there are log k rounds, so it reaches the heap's O(N log k) with no heap at all. Merging the lists into the answer one at a time instead re-walks the answer every round, which is O(N*k).

Algorithm

1. If there are no lists, return null.
2. Merge the lists in pairs, the first with the second, the third with the fourth; an odd one out is merged with nothing.
3. The merged lists are the next round's lists.
4. Repeat until one list is left, and return it.

Time & Space

Time O(N log k) for N nodes across k lists: log k rounds, each walking each node at most once. Space O(k) for a round's list of heads; no recursion.