Merge K Sorted Lists
Merge Two Sorted Lists (LC.21)
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.
Example
Input: L1 = 1->3->8->11->15->null, L2 = 2->null
Return: 1->2->3->8->11->15->nullAnalysis
It should be similar to merge two sort arrays. So we merge two lists until one list is exhausted. Then splice the results with leftovers in either L1 or L2.
Code
public ListNode mergeTwoSortedLists(ListNode l1, ListNode l2) {
// modifying the head so dummy node
ListNode dummy = new ListNode(0);
ListNode t1 = l1;
ListNode t2 = l2;
ListNode current = dummy;
// merge what they have first
while (t1 != null && t2 != null) {
if (t1.val < t2.val) {
current.next = t1;
current = current.next;
t1 = t1.next;
} else {
current.next = t2;
current = current.next;
t2 = t2.next;
}
}
// splice the rest
if (t1 != null) current.next = t1;
if (t2 != null) current.next = t2;
// return new head
return dummy.next;
}Merge K Sorted Lists (LC.23)
Merge k sorted linked lists and return it as one sorted list.
Example
Analysis
The brute force approach is to use a reduction algorithm and reduce the problem to the base case mergeTwoSortedLists. The worst case [1,2,3,4,5],[6],[7],[8],[9] can produce O(N^2) time. The classic k-way merge algorithm can be implemented in three ways. Top-down approach with divide and conquer, BFS approach with a priority queue, and bottom-up approach by merging lists in groups.
Brute Force Reduction
The brute force received Time Limit Exceeded with a large input of single number lists.
Divide and Conquer
Bottom Up Merge
Priority Queue Search
Unlike the first two approaches in which we rely on an implicit binary tree structure (height of lg(k) b/c base case is merge2lists), the priority queue uses an explicit full binary tree - heap. We keep the heap fed going down the k lists.
Reading
Wikipedia - External Merge Sort
Last updated