Merge k Sorted Lists
1 approach, code in every language
Problem description
You are given an array of k linked lists, where each individual list is already sorted in ascending order by node value.
Merge every list into a single sorted linked list and return the head of that combined list. The result must preserve ascending order across all nodes drawn from every input list.
Some of the input lists may be empty, and the whole array itself may be empty, in which case the merged result is an empty list.
Example 1
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
The three sorted lists are 1->4->5, 1->3->4 and 2->6. Interleaving them in ascending order produces 1->1->2->3->4->4->5->6.
Example 2
Input: lists = []
Output: []
There are no lists to merge, so the result is the empty list.
Constraints
k == lists.length0 <= k <= 10^40 <= lists[i].length <= 500-10^4 <= lists[i][j] <= 10^4Each lists[i] is sorted in ascending orderThe sum of lists[i].length will not exceed 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Merge Shard Streams is our own problem on the technique behind Merge k Sorted Lists: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free