Merge Two Sorted Lists

Merge two sorted linked lists into one sorted list.

Pattern

Two Pointer Merge

This problem follows the Two Pointer Merge pattern, commonly found in the Linked List category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Compare heads. Append smaller to result. Advance that pointer.

Key Insight

The dummy node eliminates the need for special-casing the head — you always have a 'previous' node to attach to.

Step-by-step

  1. 1Create a dummy node to simplify edge cases
  2. 2Compare the heads of both lists
  3. 3Append the smaller node to the result and advance that pointer
  4. 4When one list is exhausted, append the remainder of the other
  5. 5Return dummy.next

Pseudocode

dummy = ListNode(0)
curr = dummy
while l1 and l2:
    if l1.val <= l2.val:
        curr.next = l1
        l1 = l1.next
    else:
        curr.next = l2
        l2 = l2.next
    curr = curr.next
curr.next = l1 or l2
return dummy.next
Complexity Analysis

Time Complexity

O(n + m)

Space Complexity

O(1)
More Linked List Problems

Master this pattern with YeetCode

Practice Merge Two Sorted Lists and similar Linked List problems with flashcards. Build pattern recognition through active recall.

Practice this problem