Overview
You are given an array of k sorted linked lists. Merge all the linked lists into one sorted linked list and return the head.
Each linked list is a chain of nodes: { val, next }.
Constraints
0 <= k <= 10,0000 <= total nodes across all lists <= 10,000- Each list is sorted in ascending order.
- Node values are integers in range
[-10,000, 10,000].
Examples
// lists: [1->4->5, 1->3->4, 2->6]
mergeKLists([
{ val: 1, next: { val: 4, next: { val: 5, next: null } } },
{ val: 1, next: { val: 3, next: { val: 4, next: null } } },
{ val: 2, next: { val: 6, next: null } },
]);
// => 1->1->2->3->4->4->5->6mergeKLists([]); // => null mergeKLists([null]); // => null
Solution
Reveal solution
function mergeKLists(lists) {
if (!lists.length) return null;
function mergeTwoLists(a, b) {
const dummy = { val: 0, next: null };
let curr = dummy;
while (a && b) {
if (a.val <= b.val) { curr.next = a; a = a.next; }
else { curr.next = b; b = b.next; }
curr = curr.next;
}
curr.next = a || b;
return dummy.next;
}
while (lists.length > 1) {
const merged = [];
for (let i = 0; i < lists.length; i += 2) {
const a = lists[i];
const b = i + 1 < lists.length ? lists[i + 1] : null;
merged.push(mergeTwoLists(a, b));
}
lists = merged;
}
return lists[0];
}Divide and conquer: pairwise merge until one list remains. O(N log k) time.
Resources
linked-lists-combine-k-sorted.js
Linked Lists Combine K Sorted
hardcodingAlgorithmsLinked Lists
Overview
You are given an array of k sorted linked lists. Merge all the linked lists into one sorted linked list and return the head.
Each linked list is a chain of nodes: { val, next }.
Constraints
0 <= k <= 10,0000 <= total nodes across all lists <= 10,000- Each list is sorted in ascending order.
- Node values are integers in range
[-10,000, 10,000].
Examples
// lists: [1->4->5, 1->3->4, 2->6]
mergeKLists([
{ val: 1, next: { val: 4, next: { val: 5, next: null } } },
{ val: 1, next: { val: 3, next: { val: 4, next: null } } },
{ val: 2, next: { val: 6, next: null } },
]);
// => 1->1->2->3->4->4->5->6mergeKLists([]); // => null mergeKLists([null]); // => null
Solution
Reveal solution
function mergeKLists(lists) {
if (!lists.length) return null;
function mergeTwoLists(a, b) {
const dummy = { val: 0, next: null };
let curr = dummy;
while (a && b) {
if (a.val <= b.val) { curr.next = a; a = a.next; }
else { curr.next = b; b = b.next; }
curr = curr.next;
}
curr.next = a || b;
return dummy.next;
}
while (lists.length > 1) {
const merged = [];
for (let i = 0; i < lists.length; i += 2) {
const a = lists[i];
const b = i + 1 < lists.length ? lists[i + 1] : null;
merged.push(mergeTwoLists(a, b));
}
lists = merged;
}
return lists[0];
}Divide and conquer: pairwise merge until one list remains. O(N log k) time.
Resources
NameTopicDifficulty
103 of 103 problems