Skip to content

Merge Two Sorted Lists

Splice two sorted linked lists into one sorted list, always taking the smaller front node.

EasyLinked Lists
Solve on LeetCode

The problem

You get the heads of two linked lists, list1 and list2, each sorted in non-decreasing order. Merge them into one sorted list by relinking their existing nodes, and return the head of the merged list. Either list may be empty.

Input list1 = [2, 5, 9], list2 = [1, 5, 6, 12]

Output [1, 2, 5, 5, 6, 9, 12]

At every step the smaller of the two front nodes goes next, and both 5s are kept.

Input list1 = [], list2 = [3, 4]

Output [3, 4]

When one list is empty, the answer is simply the other list.

Key constraint: Reuse the existing nodes: the merged list is made by splicing them together, not by creating new ones.

How to spot the pattern

  • Two inputs that are each already sorted, and one sorted output.
  • At every step, the next output item is the smaller of the two current front items.

The idea

Both lists are sorted, so the smallest value that is left is always at the front of one of them. Compare the two front nodes, attach the smaller one to the merged list and move forward in that list. A dummy node in front of the result removes the special case for the very first node, and when one list runs out you attach the rest of the other in one step.

Brute force: Copy all values into an array, sort it and build a new list, which costs O((m + n) log(m + n)) time and creates new nodes.

Step by step

  1. 1Create a dummy node and a tail pointer that starts at it.
  2. 2While both lists have nodes, attach the smaller front node to tail.next, advance that list and move tail forward.
  3. 3When one list is empty, attach the other list's remaining nodes to tail.next.
  4. 4Return dummy.next.

See the pattern move

The linked lists pattern on a small example. Step through it, or press play.

Code

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode()
        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  # attach whatever is left
        return dummy.next

Complexity

Time

O(m + n)

Space

O(1)

Each node is attached exactly once; only the dummy node and a couple of pointers are extra.

Watch out for

  • Forgetting to attach the leftover nodes when one list ends first.
  • Returning dummy instead of dummy.next, which puts a fake node at the front.
  • Forgetting to move tail after attaching a node, so the next node overwrites it.

Follow-up questions

Can you write it recursively?

Yes: return the smaller head after setting its next to the merge of the rest. It is short, but it uses O(m + n) stack space.

How would you merge k sorted lists?

Keep the k front nodes in a min-heap, or merge the lists in pairs like merge sort; both take O(N log k) for N nodes in total. That is Merge k Sorted Lists.

In Hinglish

Dono lists ke aage wale node compare karo aur chhota wala result mein jodo. Ek list khatam ho jaaye toh doosri ka bacha hua hissa seedha jod do.

Related problems