This article provides a complete breakdown of the solution to LeetCode 23 Merge k Sorted Lists: from the problem-solving approach and algorithm steps to time and space complexity, and it also summarizes boundary cases and compares three solutions to help you understand Merge k Sorted Lists in one go.
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4-> 4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: []
Constraints:
k == lists.length0 <= k <= 10 40 <= lists[i].length <= 500-10 4 <= lists[i][j] <= 10 4lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed10 4.
Python
# Definition for singly-linked list. from typing import List, Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeKLists(self, lists : List[Optional[ListNode]]) -> Optional[ListNode]: nodes = [] head = point = ListNode(0) for left in lists: while left: nodes.append(left.val) left = left.next for x in sorted(nodes): point.next = ListNode(x) point = point.next return head.next
LeetCode Problem Extension Exercises
Other problem-solving notes in the same series are recommended for practice:
Merge k Sorted Lists Solution Approach
Merging k sorted strings has a worst-case scenario: merging them one by one in sequence, which would result in the preceding nodes being scanned k times repeatedly. Two better solutions reduce this repetitive scanning: min-heap selects the smallest head node from the k candidate head nodes each time; divide-and-conquer merge ensures that each node participates in at most log k rounds of merging.
Merge k Sorted Lists Algorithm Steps
- To construct a min-heap, put the head nodes of all k strings into it (sorted by node value).
- Create dummy nodes and tail metrics.
- Each time, the smallest node is taken from the heap and appended to the tail. If the node has a next node, the next node is pushed back into the heap.
- Repeat until the heap is empty, then return dummy.next.
Complexity analysis of Merge k Sorted Lists
| project | Complexity |
|---|---|
| Time complexity | O(N log k) |
| Space complexity | O(k) |
N is the total number of nodes. Each node enters and exits the heap once, and each operation is O(log k), so the time complexity is O(N log k). There can be at most k nodes in the heap at any given time, so the space complexity is O(k). Divide and conquer merge is also O(N log k), but the space complexity can be reduced to O(1) (iterative version).
Boundary cases and common errors in Merge k Sorted Lists
- If the input array is empty or consists entirely of empty strings, return null.
- Before pushing null head nodes into the heap, you must first exclude null head nodes, otherwise the comparison function will explode.
- Node values may be duplicated, and stacking must be able to handle the case of equality.
- If a language does not have built-in stacking, divide and conquer and merge in pairs is a better alternative for writing.
Merge k Sorted Lists: Comparison of Other Solutions
| solution | time | space | illustrate |
|---|---|---|---|
| Merge each entry into the result sequentially. | O(N·k) | O(1) | Simple to implement but suffers from severe repetitive scanning |
| Divide and conquer, then combine them in pairs. | O(N log k) | O(1) | No need for stacking, recommended alternative solution |
| min-heap | O(N log k) | O(k) | This article adopts |
