Merge K Sorted Lists
You are given an array of klists
Example 1
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Output: [1,1,2,3,4,4,5,6]
Example 2
Input: lists = []
Output: []
Output: []
Constraints:
k == lists.length0 <= k <= 104- Each list is sorted in ascending order. Total nodes across all lists ≤ 104.
Contents
Approach 1: Brute Force
Collect all values into a list, sort it, rebuild the linked list.
Java
public ListNode mergeKLists(ListNode[] lists) {
List<Integer> values = new ArrayList<>();
for (ListNode list : lists) {
while (list != null) {
values.add(list.val);
list = list.next;
}
}
Collections.sort(values);
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
for (int v : values) {
curr.next = new ListNode(v);
curr = curr.next;
}
return dummy.next;
}
// Time: O(N log N) where N = total nodes. Space: O(N)
Approach 2: Min-Heap
Always extract the globally minimum node from the k
Algorithm:
- Push the head node of each list into the min-heap (ordered by
).val - Pop the minimum node, append it to the result, then push its
node (if any) into the heap.next - Repeat until the heap is empty.
Java
public ListNode mergeKLists(ListNode[] lists) {
// Min-heap ordered by node value
PriorityQueue<ListNode> minHeap = new PriorityQueue<>(
Comparator.comparingInt(n -> n.val)
);
// Initialise heap with the head of each non-null list
for (ListNode list : lists) {
if (list != null) minHeap.offer(list);
}
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (!minHeap.isEmpty()) {
ListNode node = minHeap.poll(); // smallest current head
curr.next = node;
curr = curr.next;
if (node.next != null) {
minHeap.offer(node.next); // push the next node from the same list
}
}
return dummy.next;
}
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Brute Force | O(N log N) | O(N) |
| Min-Heap | O(N log k) | O(k): heap holds at most k nodes |
Note: N = total number of nodes across all lists, k = number of lists.