Skip to content
Problem · Canonical Warm-Up
easydummy-head · two-pointer · iterativeTime · O(m + n)Space · O(1)

Merge Two Sorted Lists

Problem statement

Statement

You are given the heads of two sorted linked lists, list1 and list2. Merge them into a single sorted list by splicing together the existing nodes, and return the head of the result.

Examples

list1 = [1, 2, 4], list2 = [1, 3, 4]
-> [1, 1, 2, 3, 4, 4]

list1 = [], list2 = []
-> []

list1 = [], list2 = [0]
-> [0]

list1 = [5], list2 = [1, 2, 3]
-> [1, 2, 3, 5]      (one list is exhausted long before the other)

Constraints

  • Each list holds between 0 and 50 nodes.
  • -100 <= Node.val <= 100
  • Both lists are sorted in non-decreasing order, so equal values may appear in either or both.
  • The result must reuse the input nodes. Allocating a fresh list of copies is a different, worse answer.

What this problem is really testing

This is the merge step of merge sort, extracted and handed to you on its own. The algorithm is three lines and nobody gets it wrong. What people get wrong is pointer bookkeeping: where the head comes from, what happens on the first iteration, and what happens to the tail of the list that did not run out. Those three questions are the problem.

The idea worth taking away is the sentinel, and the cleanest way to see it is as scaffolding. A builder erects scaffolding not because the building needs it but because it makes every floor reachable by the same method, and then takes it down. A dummy node does the same for list construction: without it, attaching the first node is a special case (you must decide which head wins and assign it to a variable that does not exist yet) while attaching every subsequent node is a uniform curr.next = node. With it, the first attachment is just another curr.next = node, and you throw the scaffolding away by returning dummy.next. One allocation buys the deletion of an entire branch.

The second thing under test is whether you notice that the leftover tail needs no loop. Once one list is exhausted, the other is already sorted and already linked, so a single pointer assignment splices all of it on in O(1). Candidates who write a second while loop to copy the remainder have not understood that they are moving pointers, not values.