Merge Two Sorted Lists (LeetCode 21): Solution and Explanation

Easy
Linked List
Recursion

You are given the heads of two linked lists, each already sorted in non-decreasing order, and must combine them into one sorted list. The result should reuse the existing nodes by relinking them rather than allocating new ones.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The lazy approach is to pour every value into an array, sort it, and build a new list. That costs O((n + m) log(n + m)) time and ignores the fact that both inputs are already sorted, which is the whole hint of the problem.

Because both lists are sorted, the smallest remaining value overall must be at the head of one of them. So you only ever need to compare two nodes: the current front of each list. Take the smaller one, attach it to the output, advance in the list it came from, and repeat. This is exactly the merge step of merge sort, applied to linked lists.

The fiddly part with linked lists is the very first node, since you do not know in advance which list provides the head. A dummy node removes that special case. You always append to tail.next, and at the end the real head is simply dummy.next. When one list runs out, the other one is already sorted and can be attached in a single pointer assignment, so there is no need to loop over the leftovers.

Approach: Iterative merge with a dummy head

  1. Create a dummy node and set tail = dummy. The dummy's next will become the merged list's head.
  2. While both list1 and list2 are non-empty, compare list1.val with list2.val.
  3. If list1.val is smaller, link tail.next to list1 and advance list1. Otherwise link tail.next to list2 and advance list2.
  4. Move tail forward to the node just attached.
  5. After the loop, at most one list still has nodes. Attach whichever is non-empty to tail.next.
  6. Return dummy.next, which skips the placeholder node.

Step-by-step example

list1 = [1,2,4], list2 = [1,3,4]
  1. Compare 1 and 1. Since list1.val < list2.val is false on a tie, take 1 from list2. Output: 1.
  2. Compare 1 from list1 with 3. Take 1 from list1. Output: 1, 1.
  3. Compare 2 with 3. Take 2 from list1. Output: 1, 1, 2.
  4. Compare 4 with 3. Take 3 from list2. Output: 1, 1, 2, 3.
  5. Compare 4 with 4. The tie goes to list2 again, so take its 4, and list2 is now empty.
  6. Attach the rest of list1, which is the single node 4. The result is [1,1,2,3,4,4].

Code: Python, Java, C++

1class Solution:
2    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
3        dummy = ListNode()
4        tail = dummy
5        
6        while list1 and list2:
7            if list1.val < list2.val:
8                tail.next = list1
9                list1 = list1.next
10            else:
11                tail.next = list2
12                list2 = list2.next
13            tail = tail.next
14            
15        if list1:
16            tail.next = list1
17        elif list2:
18            tail.next = list2
19            
20        return dummy.next

Time and space complexity

Time

O(n + m)

Each comparison places exactly one node into the result, so the loop runs at most n + m times, and the final splice of the leftover list is a single assignment.

Space

O(1)

The merge only relinks existing nodes. Apart from the dummy node and a couple of pointers, nothing extra is allocated.

Other approaches

Recursive merge (time O(n + m), space O(n + m))

Return the smaller head and set its next to the merge of the remaining lists. It is short and elegant, but every node adds a stack frame, so very long lists can hit recursion limits.

Collect and sort (time O((n + m) log(n + m)), space O(n + m))

Copy all values into an array, sort it, and build a new list. It is simple but ignores the existing order and allocates new nodes.

Common mistakes

  • Forgetting to advance tail after attaching a node, which makes every new node overwrite the previous link.
  • Looping over the leftover list node by node instead of attaching it directly. It works but is unnecessary since the remainder is already sorted and linked.
  • Returning dummy instead of dummy.next, which puts a stray 0 at the front of the result.
  • Not handling an empty input. If either list starts empty, the loop is skipped and the other list must still be returned through the final splice.

Frequently asked questions

Why use a dummy node when merging linked lists?

Without a dummy, you need special code to pick the head before the loop starts. The dummy gives you a fixed node to append to, so every step looks the same and the real head is just dummy.next.

Is the recursive solution better than the iterative one?

Both run in O(n + m) time. The iterative version uses O(1) extra space, while recursion uses a stack frame per node, so the iterative version is safer for long lists.

Is the merge stable when values are equal?

This code takes from list2 on ties because it uses a strict less-than comparison. If you need nodes from list1 to come first on equal values, change the comparison to <=.

How does this relate to Merge K Sorted Lists?

Merging two lists is the building block for merging k lists. You can merge the k lists in pairs, halving the count each round, or use a min-heap that always exposes the smallest current head. Both reach O(N log k) time for N total nodes.