Merge Two Sorted Lists
The problem
Section titled “The problem”You get the heads of two linked lists, each sorted in ascending order. Join them into one sorted list by reusing their existing nodes, and return its head.
[1, 2, 4] and [1, 3, 4] -> [1, 1, 2, 3, 4, 4]Key insight
Section titled “Key insight”The smallest remaining value is always at the front of one of the two lists, so you only ever compare two nodes. This is the merge step of merge sort.
Keep a tail pointer to the end of the list you are building. Repeatedly attach the
smaller front node to tail and advance that list. The awkward part is the very first
node: which list does the result start with? A dummy head removes the question. You
build after the dummy and return dummy.next. When one list runs out, the other is
already sorted, so attach it in one step.
Show solutionHide solution
def merge_two_lists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: dummy = tail = ListNode() # dummy head: no special case for the first node while list1 and list2: if list2.val < list1.val: list1, list2 = list2, list1 # keep the smaller node in list1 tail.next = list1 tail = list1 list1 = list1.next tail.next = list1 or list2 # splice on whatever remains return dummy.nextexport function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { const dummy = new ListNode(); // dummy head: no special case for the first node let tail = dummy; while (list1 && list2) { if (list1.val <= list2.val) { tail.next = list1; list1 = list1.next; } else { tail.next = list2; list2 = list2.next; } tail = tail.next; } tail.next = list1 ?? list2; // splice on whatever remains return dummy.next;}class Solution { public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(); // dummy head: no special case for the first node ListNode tail = dummy; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { tail.next = list1; list1 = list1.next; } else { tail.next = list2; list2 = list2.next; } tail = tail.next; } tail.next = list1 != null ? list1 : list2; // splice on whatever remains return dummy.next; }}Complexity
Section titled “Complexity”- Time: O(n + m) — each node is attached exactly once.
- Space: O(1) — you relink existing nodes and allocate only the dummy. (A recursive version is O(n + m) because of the call stack.)
Watch out for
Section titled “Watch out for”- Forgetting the leftover. After the loop one list is empty and the other may still
have nodes. Attach it with
tail.next = list1 or list2. - Returning
dummyinstead ofdummy.next. - Empty inputs. If both are empty the loop is skipped and you return
None. If one is empty the leftover step handles it. - Don’t create new nodes. It works but wastes O(n + m) space and misses the point.
Variations
Section titled “Variations”Merge k Sorted Lists (LeetCode 23)
Section titled “Merge k Sorted Lists (LeetCode 23)”Merge k sorted lists. The trick: keep the k current heads in a min-heap, pop the
smallest, attach it, and push its successor. O(N log k) for N total nodes. Or merge
pairs of lists repeatedly, halving the count each round.
Sort List (LeetCode 148)
Section titled “Sort List (LeetCode 148)”Sort a linked list in O(n log n) time. The trick: merge sort. Split at the middle found with fast and slow pointers, sort each half recursively, and merge them with this exact function.
Merge Sorted Array (LeetCode 88)
Section titled “Merge Sorted Array (LeetCode 88)”Merge two sorted arrays, where the first has spare space at its end. The trick: the same merge, but fill from the back so you never overwrite values you still need.