Merge Two Sorted Lists
Difficulty: Easy
Given the heads of two linked lists, each sorted in increasing order, merge them into one sorted list and return its head.
Reuse the existing nodes instead of creating new ones — just re-link the pointers so the values come out in order.
Examples
Input: list1 = [1, 2, 4], list2 = [1, 3, 4]
Output: [1, 1, 2, 3, 4, 4]
Input: list1 = [], list2 = []
Output: []
Input: list1 = [], list2 = [0]
Output: [0]
Constraints
The number of nodes in each list is between 0 and 50.
-100 <= Node.val <= 100
Both lists are sorted in non-decreasing order.
Approach
You could put every value in one collection, sort it, and rebuild a list. That works, but it ignores that the lists are already sorted, so you pay for a sort you don't need.
Instead, walk both lists side by side with two pointers. At each step, attach the smaller front node to the result and advance only that pointer. When one list runs out, attach the rest of the other. This merges the lists in one pass.
Solutions
Brute Force — Collect, Sort, Rebuild
Copy every value from both lists into an array, sort it, and build a new list from it. This ignores that the inputs are already sorted, so it does more comparisons than needed.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function mergeTwoLists(list1, list2) {
const values = [];
let node = list1;
while (node) {
values.push(node.val);
node = node.next;
}
node = list2;
while (node) {
values.push(node.val);
node = node.next;
}
values.sort((a, b) => a - b);
const dummy = new ListNode(0);
let curr = dummy;
for (const value of values) {
curr.next = new ListNode(value);
curr = curr.next;
}
return dummy.next;
}Time: O((n + m) log(n + m)) · Space: O(n + m)
Optimal — Two-Pointer Merge
Keep one pointer on each list. Compare the front values, attach the smaller node to the result, and advance only that pointer.
A dummy node at the front gives the first real node somewhere to attach without a special case. When one list runs out, the rest of the other is already sorted, so attach it in one step.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function mergeTwoLists(list1, list2) {
const dummy = new ListNode(0);
let curr = dummy;
while (list1 !== null && list2 !== null) {
if (list1.val <= list2.val) {
curr.next = list1;
list1 = list1.next;
} else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
// At most one of these still has nodes left, and they're already sorted.
curr.next = list1 !== null ? list1 : list2;
return dummy.next;
}Time: O(n + m) · Space: O(1) — reuses existing nodes