LeetCode #21 Easy

Merge Two Sorted Lists

Merge Two Sorted Lists is LeetCode 21 (Easy). You get the heads of two singly linked lists, list1 and list2, each sorted in non-decreasing order.

  • Join them into one sorted list by splicing the existing nodes together, not by creating new ones.
  • Return the head of the merged list.
  • Either list, or both, may be empty.
Constraints
  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.
linked-listrecursion
Open on LeetCode ↗
02

Intuition

Both lists are sorted, so the smallest node left is always one of the two current heads. Take the smaller head, attach it to the result, and repeat. This is the merge step of merge sort, done with pointers instead of array copies.

  • Dummy node: start the result with a throwaway node and a tail pointer on it. Every attach is then tail.next = node, with no special case for the first node.
  • Leftover in one link: when one list runs out, the other is still sorted and no smaller than tail, so one assignment attaches all of it.
How to spot this pattern

Building a linked list from front to back while choosing nodes from more than one source. A dummy head plus a tail pointer is the standard tool whenever the first node of the answer is not known in advance.

03

Approach

Try it first

Before reading on, decide which two nodes could be the smallest in the merged list, and what you do with the rest of one list once the other is empty. Aim for O(m + n) time and no new nodes.

1

Create a dummy node and a tail

Make dummy = ListNode() and set tail = dummy. The dummy gives tail a node to attach to before the result has any real node, so the loop body never needs an empty-result check.

2

Attach the smaller head

While both lists are non-empty, compare list1.val and list2.val. Set tail.next to the smaller node and advance that list. Taking list1 on a tie keeps equal values in their original order.

3

Move the tail forward

Set tail = tail.next after each attach, so tail is always the last node of the result and the next attach is O(1).

4

Attach whatever is left

When the loop ends, at most one list still has nodes. Set tail.next = list1 or list2. The leftover is already sorted and starts at a value no smaller than tail, so it can be linked as a whole.

5

Return the node after the dummy

Return dummy.next. The dummy was only scaffolding; if both inputs were empty, dummy.next is still None, which is the correct empty answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def mergeTwoLists(self, list1, list2):
▶3 dummy = tail = ListNode()
▶4 while list1 and list2:
▶5 if list1.val <= list2.val:
▶6 tail.next = list1
▶7 list1 = list1.next
▶8 else:
▶9 tail.next = list2
▶10 list2 = list2.next
▶11 tail = tail.next
▶12 tail.next = list1 or list2
▶13 return dummy.next
list1124list2134resultDtaildummy node D, tail points at it
list11 → 2 → 4
list21 → 3 → 4
The dummy node D is a placeholder in front of the answer. tail always points at the last node of the result, so attaching the next node is the same single line every time, even for the very first one.
list1124list2134resultD1tailtie at 1 → take list1's 1
compare1 vs 1
result1
Both heads are 1. Taking list1's node on a tie keeps equal values in their original list order. tail.next now points at it, and tail moves onto it.
list1124list2134resultD11tail1 < 2 → take list2's 1
compare2 vs 1
result1 → 1
The smaller head, 1, is the smallest value left in either list, because each list is sorted. It is spliced after tail, and tail moves onto it.
list1124list2134resultD112tail2 < 3 → take list1's 2
compare2 vs 3
result1 → 1 → 2
The smaller head, 2, is the smallest value left in either list, because each list is sorted. It is spliced after tail, and tail moves onto it.
list1124list2134resultD1123tail3 < 4 → take list2's 3
compare4 vs 3
result1 → 1 → 2 → 3
The smaller head, 3, is the smallest value left in either list, because each list is sorted. It is spliced after tail, and tail moves onto it.
list1124list2134resultD11234tailtie at 4 → take list1's 4
compare4 vs 4
result1 → 1 → 2 → 3 → 4
Both heads are 4. Taking list1's node on a tie keeps equal values in their original list order. tail.next now points at it, and tail moves onto it.
list1124list2134resultD112344taillist1 is empty → link the rest of list2 in one step
attached1 node
result1 → 1 → 2 → 3 → 4 → 4
One list is empty. The other is still sorted and every value in it is at least as big as tail's, so one assignment, tail.next = the rest, attaches the remaining node with no loop.
list1124list2134resultD112344headanswer: the list after D
returned1 → 1 → 2 → 3 → 4 → 4
Return dummy.next: the dummy was only scaffolding, and the real answer starts at the node after it. No new nodes were created; every node was relinked.
05

Recursive merge

If either list is empty, the answer is the other one. Otherwise the smaller head comes first, and its next is the merge of the remaining nodes. Each call handles one node, so the call stack grows to m + n frames.

▶1class Solution:
▶2 def mergeTwoLists(self, list1, list2):
▶3 if not list1 or not list2:
▶4 return list1 or list2
▶5 if list1.val <= list2.val:
▶6 list1.next = self.mergeTwoLists(list1.next, list2)
▶7 return list1
▶8 list2.next = self.mergeTwoLists(list1, list2.next)
▶9 return list2
06

Common pitfalls

Forgetting the leftover nodes

✗ Wrong
while list1 and list2:
    ...
return dummy.next
✓ Right
while list1 and list2:
    ...
tail.next = list1 or list2
return dummy.next

With list1 = [1, 2] and list2 = [3, 4, 5], the loop stops once 1 and 2 are attached and returns [1, 2]. The nodes 3, 4 and 5 are never linked.

Not moving the tail

✗ Wrong
tail.next = list1
list1 = list1.next
✓ Right
tail.next = list1
list1 = list1.next
# after the if/else:
tail = tail.next

With [1, 2] and [3], every attach overwrites dummy.next, and the final leftover link overwrites it once more. The answer comes back as [3] instead of [1, 2, 3].

Returning the dummy itself

✗ Wrong
return dummy
✓ Right
return dummy.next

With [1] and [2], this returns [0, 1, 2]: the placeholder value 0 shows up as an extra first node.

07

Edge cases

One list empty

The loop never runs and tail.next = list1 or list2 returns the other list unchanged.

Both lists empty

Nothing is attached, so dummy.next is None, the empty list.

08

Complexity

Time
O(m + n)
Space
O(1)
Each node is attached once, and the leftover in a single step. Only the dummy node and two pointers are added; the input nodes are reused.
09

Merge Two Sorted Lists FAQ

Why is splicing O(1) space if the output has m + n nodes?

The output is made of the input nodes themselves. Only their next pointers change, so no node is allocated except the dummy. Building fresh nodes with copied values would use O(m + n).

How does this extend to k sorted lists?

Merging lists one by one into a growing result costs O(k · N) for N total nodes. Merging them in pairs, or keeping the k current heads in a min-heap, brings it down to O(N log k).