Skip to main content
20

Merge Two Sorted Lists

Easylinked list

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Linked ListRead the beginner guide

You're given the heads of two linked lists, list1 and list2, each sorted in ascending order. Merge them into one sorted list by linking their existing nodes together, and return its head.

Understand the problem

  • Both lists are already sorted from smallest to largest.
  • You must combine them into a single list that's also sorted.
  • Splicing means you reuse the nodes you were given and just change their next pointers. You don't need to create new nodes.
  • Either list may be empty.

Think of two sorted piles of numbered cards, face up. To merge them into one sorted pile, you keep taking the smaller of the two top cards.

Example 1

text
Input:  list1 = [1, 2, 4], list2 = [1, 3, 4]
Output: [1, 1, 2, 3, 4, 4]

Example 2

text
Input:  list1 = [], list2 = [0]
Output: [0]

One list is empty, so the answer is just the other list.

Example 3

text
Input:  list1 = [], list2 = []
Output: []

Constraints

  • 0 <= number of nodes in each list <= 50
  • -100 <= Node.val <= 100
  • Both lists are sorted in non-decreasing order.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Repeatedly take the smaller of the two front nodes and attach it to the end of a growing merged list, starting from a dummy node so the first attachment isn't a special case.

    The naive approach (and its cost)

    Copy every value from both lists into an array, sort it, and build a new list from it. It works, but sorting costs O((n + m) log(n + m)), and it ignores the fact that both lists are already sorted. It also creates new nodes instead of reusing the ones you were given.

    The key insight

    Since both lists are sorted, the smallest remaining value is always at the front of one of them. So merging is just: compare the two fronts, take the smaller, repeat. Each comparison places one node, so it's linear.

    The dummy node trick. Building a list one node at a time means doing tail.next = node. But for the first node, there's no tail yet, so you'd need an if for "is the result still empty?". Instead, start with a fake node:

    Loading diagram...

    tail starts at dummy. Now every attachment, including the first, is the same tail.next = node. At the end, return dummy.next, skipping the fake node.

    Step by step

    list1 = 1 → 2 → 4, list2 = 1 → 3 → 4:

    list1 frontlist2 frontTake (smaller, list1 on ties)Merged list so far
    111 from list11
    211 from list21 → 1
    232 from list11 → 1 → 2
    433 from list21 → 1 → 2 → 3
    444 from list11 → 1 → 2 → 3 → 4
    (empty)4attach the rest of list21 → 1 → 2 → 3 → 4 → 4

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n + m). Each node is attached exactly once.
    • Memory: O(1). We only rewire existing nodes, plus one dummy node.

    Common mistakes

    • Forgetting to advance tail. If tail stays put, each new node overwrites the last one.
    • Looping over the leftover list one node at a time. It works, but tail.next = list1 ?? list2 attaches the whole rest in one step.
    • Returning dummy instead of dummy.next. The dummy is a helper, not part of the answer.

    Going deeper

    • Taking from list1 on ties (<=) keeps the merge stable: equal values stay in their original order. That matters when merge sort uses this step to sort records.
    • This merge is the building block of Merge K Sorted Lists and of merge sort itself.
    • A recursive version also works: if (a.val <= b.val) { a.next = merge(a.next, b); return a }, but it uses O(n + m) stack space.

    Reference solution

    js
    /**
     * @param {ListNode | null} list1
     * @param {ListNode | null} list2
     * @return {ListNode | null}
     */
    export default function mergeTwoLists(list1, list2) {
      // A fake first node, so attaching the first real node isn't a special case.
      const dummy = new ListNode()
      let tail = dummy // the last node of the merged list so far
      while (list1 && list2) {
        // Take the smaller front node (list1 on ties keeps equal values in order).
        if (list1.val <= list2.val) {
          tail.next = list1
          list1 = list1.next
        } else {
          tail.next = list2
          list2 = list2.next
        }
        tail = tail.next // the node we just attached is the new end
      }
      // One list is empty: the rest of the other is already sorted, attach it whole.
      tail.next = list1 ?? list2
      return dummy.next // skip the fake node
    }
    ts
    export default function mergeTwoLists(
      list1: ListNode | null,
      list2: ListNode | null,
    ): ListNode | null {
      // A fake first node, so attaching the first real node isn't a special case.
      const dummy = new ListNode()
      let tail = dummy // the last node of the merged list so far
      while (list1 && list2) {
        // Take the smaller front node (list1 on ties keeps equal values in order).
        if (list1.val <= list2.val) {
          tail.next = list1
          list1 = list1.next
        } else {
          tail.next = list2
          list2 = list2.next
        }
        tail = tail.next // the node we just attached is the new end
      }
      // One list is empty: the rest of the other is already sorted, attach it whole.
      tail.next = list1 ?? list2
      return dummy.next // skip the fake node
    }
    python
    def merge_two_lists(list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
        # A fake first node, so attaching the first real node isn't a special case.
        dummy = ListNode()
        tail = dummy  # the last node of the merged list so far
        while list1 and list2:
            # Take the smaller front node (list1 on ties keeps equal values in order).
            if list1.val <= list2.val:
                tail.next, list1 = list1, list1.next
            else:
                tail.next, list2 = list2, list2.next
            tail = tail.next  # the node we just attached is the new end
        # One list is empty: the rest of the other is already sorted, attach it whole.
        tail.next = list1 or list2
        return dummy.next  # skip the fake node