Example 1
- Input
- lists = [[1,4,5],[1,3,4],[2,6]]
- Output
- [1,1,2,3,4,4,5,6]
The three sorted chains weave into 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6.
You are given an array of k linked lists that are each sorted in ascending order. Merge them into one sorted linked list and return its head.
You are given an array lists of k linked lists, where each list is sorted in ascending order and any entry may be empty.
Merge all the lists into one sorted linked list and return its head, reusing the existing nodes where possible. The total number of nodes across all lists is bounded, while k alone can be large.
Lists are terminating, independently owned chains. The rebuilding baseline creates fresh nodes and preserves every input. The pairwise approach splices original nodes and updates the lists array, so callers must allow those mutations.
k == lists.length0 <= k <= 10^40 <= lists[i].length <= 500-10^4 <= lists[i][j] <= 10^4lists[i] is sorted in ascending order.lists[i].length does not exceed 10^4.The three sorted chains weave into 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6.
No lists means the merged result is empty.
One empty list still merges to an empty result.
Skip the empty chains, interleave the negative heads in ascending order, and retain all three occurrences of -1. Equal values belong to separate nodes and must not be deduplicated.
The smallest remaining value of any sorted chain is at its head. Merging two chains repeatedly takes the smaller head, then attaches an already sorted remainder when one side ends. In Example 1, merging [1,4,5] with [1,3,4] gives [1,1,3,4,4,5]; merging that result with [2,6] gives the answer. Pair lists in balanced rounds so a node participates in at most logarithmically many merges, instead of being rescanned after every newly added list. Empty array entries still cost work to inspect, even when there are few or no nodes.
Reveal Collect Sort Rebuild: intuition, complexity, and code
k chains collapse in logarithmic rounds instead of one-by-one.null without entering any merge round.k.lists[0] when no list exists.When many sorted chains must become one, merge pairs in halving rounds so linear two-way merges stack into logarithmic depth.