Merge In Between Linked Lists (LeetCode 1669): Solution and Explanation

Medium
Linked List

Given two linked lists and two positions a and b, remove nodes a through b of list1 and put the whole of list2 in their place. Return the head of the result.

Intuition

Splicing one list into another only changes two links: the link coming into the cut section and the link going out of it. Everything else stays where it is.

The link into the cut belongs to the node at position a - 1. The link out of the cut must end at the node at position b + 1. Find those two nodes first and the rest is two assignments.

list2 has no tail pointer, so we walk it once to find its last node. That last node is the one that has to point at the node after the cut.

Because a is at least 1, the head of list1 is never removed, so the answer is always list1 itself.

Approach: Two anchors and two rewires

  1. Walk prev from the head a - 1 steps so it sits on the node just before the cut.
  2. Start after at prev and walk it b - a + 2 steps so it sits on the node just after the cut.
  3. Set prev.next = list2. The nodes from a to b are now unreachable.
  4. Walk tail from list2's head to its last node, then set tail.next = after.
  5. Return list1.

Step-by-step example

list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
  1. prev starts on 10 and takes a - 1 = 2 hops, landing on 13 at position 2.
  2. after starts on 13 and takes b - a + 2 = 3 hops: 6, 9, then 5 at position 5.
  3. prev.next = list2, so 13 now points at 1000000. Nodes 6 and 9 drop out.
  4. tail walks list2 to 1000002 and sets its next to 5.
  5. Return list1: [10,1,13,1000000,1000001,1000002,5].

Code: Python, Java, C++

1class Solution:
2    def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
3        prev = list1
4        for _ in range(a - 1):
5            prev = prev.next
6        after = prev
7        for _ in range(b - a + 2):
8            after = after.next
9        prev.next = list2
10        tail = list2
11        while tail.next:
12            tail = tail.next
13        tail.next = after
14        return list1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

We walk at most b + 1 nodes of list1 and every node of list2 once.

Space

O(1)

Only three pointers are used; the nodes are relinked in place.

Other approaches

Copy into an array and rebuild (time O(n + m), space O(n + m))

Read both lists into arrays, build the merged array with slicing, and create new nodes from it. Simple to reason about but allocates O(n + m) extra memory.

Single pass with an index counter (time O(n + m), space O(1))

Walk list1 once with a counter and record the nodes at positions a - 1 and b + 1 as you pass them. Same cost as the two-walk version, just written as one loop.

Common mistakes

  • Stopping after on node b instead of node b + 1. Then the last removed node stays in the list.
  • Walking prev a steps instead of a - 1, which lands on the first node to remove instead of the one before it.
  • Rewiring prev.next before finding after while also walking after from prev.next. Once prev.next points at list2, that walk goes into the wrong list.
  • Forgetting to walk to list2's tail and linking list2's head to after instead, which drops all of list2 except its first node.

Frequently asked questions

Why does after take b - a + 2 steps from prev?

prev is at position a - 1 and after must reach position b + 1. The difference is (b + 1) - (a - 1) = b - a + 2.

Do I need a dummy node?

No. The constraints guarantee a is at least 1 and b is less than n - 1, so both anchor nodes always exist and the head never changes.

Do the removed nodes need to be freed?

In Python, Java, JavaScript, C# and Go the garbage collector reclaims them once nothing points at them. In C++ you could delete them, but the judge does not require it.