The Runtime Theory
easyleetcode#linked-list#two-pointers

Merge Two Sorted Lists

Merge two sorted linked lists into one sorted list using a dummy-node sentinel and iterative two-pointer walk — classic linked-list merge.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

inlist1=[1,2,4], list2=[1,3,4]

out[1,1,2,3,4,4]

inlist1=[], list2=[]

out[]

inlist1=[], list2=[0]

out[0]

Given the heads of two sorted singly linked lists, merge them into one sorted list. The machine must splice the two chains together by rewriting next pointers — it never allocates new nodes, it just relinks existing ones.

The key insight: rather than special-casing the empty-result head, use a dummy node as a sentinel. The result pointer stays fixed at the dummy while a tail pointer walks forward, so the merge loop body stays identical for the first element and every subsequent element.

Approach:

  1. Create dummy = ListNode(0) and point tail at it.
  2. While both lists are non-empty, attach the smaller head to tail.next and advance that list.
  3. When one list empties, attach the remainder of the other wholesale — it is already sorted.
python
def merge_two_lists(l1, l2):
    dummy = tail = ListNode(0)
    while l1 and l2:
        if l1.val <= l2.val:
            tail.next, l1 = l1, l1.next
        else:
            tail.next, l2 = l2, l2.next
        tail = tail.next
    tail.next = l1 or l2
    return dummy.next

Time: O(n + m), every node visited once. Space: O(1) besides the dummy.

Trickiest edge case: one list empty from the start — the loop never runs and tail.next = l1 or l2 handles it, which is why the final attachment must be outside the loop.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.