ToolMight Logo
EasyLinked ListDummy HeadPointer SplicingTwo Pointers

Merge Two Sorted Lists

Splice two sorted linked lists together into one non-decreasing linked list. Compare O(1)-space iterative dummy-head splicing against recursive pointer linking.

Optimal Time
O(n + m)
Optimal Space
O(1)
Primary Pattern
Dummy Head
Visualizer
Open Interactive View →

Problem Statement

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Examples & Constraints

Example 1
Input: list1 = [1, 2, 4], list2 = [1, 3, 4]
Output: [1, 1, 2, 3, 4, 4]
Explanation: Comparing node values from both heads yields a sorted merged sequence.
Example 2
Input: list1 = [], list2 = [0]
Output: [0]
Explanation: One list is empty, so the merged output is simply the non-empty list.
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.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Building or rearranging a linked list head cleanly uses a dummy sentinel node so head insertion uses the identical logic as every middle insertion.

Core Invariant

At every step, tail points to the last merged node and every earlier node is sorted; splicing whichever head is smaller preserves sorted order across the chain.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Iterative Splicing with Dummy HeadOptimal
O(n + m)O(1)Use a dummy head node and a current pointer to stitch existing nodes together in O(1) auxiliary space without allocating new nodes.
2. Recursive Head Selection
O(n + m)O(n + m)Recursively pick the smaller head node between list1 and list2 and attach the recursive merge of the remaining tails to its next pointer.

1. Iterative Splicing with Dummy Head

Optimal
TimeO(n + m)
SpaceO(1)

Use a dummy head node and a current pointer to stitch existing nodes together in O(1) auxiliary space without allocating new nodes.

Time ComplexityO(n + m)

Every node across both input lists of lengths N and M is visited and linked exactly once.

Space ComplexityO(1)

No new nodes are created. Only a single dummy node and pointer references are used.

How It Works

The Dummy Head Technique: Eliminating Edge Cases

In linked list manipulation, the most common source of null pointer exceptions is deciding which node becomes the head of the merged list.

By initializing a sentinel dummy node (dummy) and a tracking pointer (tail = dummy):

  1. We never have to write special branches for the first node insertion.
  2. While both list1 and list2 are non-null:
  • If list1.val <= list2.val, wire tail.next = list1 and advance list1 = list1.next.
  • Else, wire tail.next = list2 and advance list2 = list2.next.
  • Advance tail = tail.next.
  1. When one list runs out of nodes, attach the remaining tail directly: tail.next = (list1 != null) ? list1 : list2.
  2. Return dummy.next as the true head of the merged list.

In-Place Pointer Rewiring

Notice that we do not allocate any new list nodes! We only change the next pointers of the existing input nodes. This guarantees O(1) auxiliary memory.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Initialize Dummy

Create dummy node (-1). tail points to dummy. list1 at 1, list2 at 1.

State:tail -> dummylist1: 1->2->4list2: 1->3->4
Strengths
  • +Optimal O(1) auxiliary space
  • +Clean logic without edge cases thanks to dummy head
Trade-offs
  • -Mutates original list nodes (expected when splicing in place)

Reference Implementation

Complete implementation for Iterative Splicing with Dummy Head in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
dummy = ListNode(-1)
tail = dummy
while list1 and 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 if list1 else list2
return dummy.next
def to_list(head: ListNode | None) -> list[int]:
res = []
curr = head
while curr:
res.append(curr.val)
curr = curr.next
return res
if __name__ == "__main__":
l1 = ListNode(1, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
merged = merge_two_lists(l1, l2)
print("Merged list:", to_list(merged))

2. Recursive Head Selection

TimeO(n + m)
SpaceO(n + m)

Recursively pick the smaller head node between list1 and list2 and attach the recursive merge of the remaining tails to its next pointer.

Time ComplexityO(n + m)

One recursive step executes per node across both lists.

Space ComplexityO(n + m)

Consumes stack frames proportional to total combined list length n + m.

How It Works

Recursive Head Comparison

Suppose you have list1 and list2:

  • Base cases: if list1 == null, return list2; if list2 == null, return list1.
  • Inductive step: if list1.val <= list2.val, list1 belongs first, so set list1.next = mergeTwoLists(list1.next, list2) and return list1. Otherwise attach onto list2.next and return list2.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Compare Heads 1 vs 1

list1.val (1) <= list2.val (1). Pick list1(1) and recurse on merge([2, 4], [1, 3, 4]).

State:head = list1(1)
Strengths
  • +Compact 8-line recursive definition without dummy nodes
Trade-offs
  • -Consumes O(n + m) call-stack frames — risky on very long lists (>10^4 nodes)

Reference Implementation

Complete implementation for Recursive Head Selection in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def merge_two_lists_rec(list1, list2):
if not list1:
return list2
if not list2:
return list1
if list1.val <= list2.val:
list1.next = merge_two_lists_rec(list1.next, list2)
return list1
list2.next = merge_two_lists_rec(list1, list2.next)
return list2
Interactive Visualizer

Trace Singly Linked List mechanics in memory

Step through custom inputs in the Singly Linked List visualizer to inspect pointer updates, array shifts, and call-stack state alongside Merge Two Sorted Lists.

Open Singly Linked List visualizer

Frequently Asked Questions

Why is a dummy node so useful when merging linked lists?

A sentinel dummy node removes special cases for setting the initial head pointer. Both empty-list and non-empty-list cases append onto tail.next uniformly, and returning dummy.next gives the true merged head.

Does merging two sorted lists allocate new list nodes?

No. Both iterative splicing and recursive linking reuse existing node allocations by rewiring .next pointers (O(1) auxiliary space iteratively).

Should I use iterative or recursive merge in interviews?

Prefer the iterative dummy-head version because it achieves O(1) extra space and cannot overflow the call stack when lists exceed tens of thousands of nodes.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • One or both lists empty (list1 = [], list2 = [0] or [], []) returns the non-empty head or null.
  • Lists of completely skewed sizes ([1] and [2, 3, 4, 5]) attach the remaining list in O(1) once the shorter ends.
  • Duplicate node values across list1 and list2 (e.g., [1, 2, 4] + [1, 3, 4]) preserve both copies stably.

Common Bugs to Avoid

  • Continuing to iterate node-by-node over the remaining list after the other hits null instead of linking `tail.next = list1 || list2` directly.
  • Returning `dummy` instead of `dummy.next`, exposing the placeholder node `-1` as the head.
  • Writing complex `if (head == null)` branches instead of allocating a dummy sentinel.

Interview Follow-Up Variations

  • Merge k Sorted Lists: extend from 2 heads to a size-k Min-Heap (or pairwise divide-and-conquer merging in O(N log k)).
  • Sort List (Merge Sort on Linked Lists): split via fast/slow pointers and recombine via mergeTwoLists.

Related Problems

All problems
EasyLinked List

Reverse Linked List

Reverse a singly linked list in-place by flipping next pointers. Compare O(1)-space three-pointer iteration with recursive tail rewiring.

Pattern: Pointer Reversal
O(n) · O(1)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyLinked List

Linked List Cycle

Detect whether a linked list loops back on itself. Compare O(n)-space node-identity tracking against Floyd's O(1)-space fast-and-slow pointer algorithm.

Pattern: Fast and Slow Pointers
O(n) · O(1)
Solve