Merge In Between Linked Lists (LeetCode 1669): Solution and Explanation
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
- Walk
prevfrom the heada - 1steps so it sits on the node just before the cut. - Start
afteratprevand walk itb - a + 2steps so it sits on the node just after the cut. - Set
prev.next = list2. The nodes from a to b are now unreachable. - Walk
tailfrom list2's head to its last node, then settail.next = after. - Return
list1.
Step-by-step example
list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
- prev starts on 10 and takes a - 1 = 2 hops, landing on 13 at position 2.
- after starts on 13 and takes b - a + 2 = 3 hops: 6, 9, then 5 at position 5.
- prev.next = list2, so 13 now points at 1000000. Nodes 6 and 9 drop out.
- tail walks list2 to 1000002 and sets its next to 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 list11class Solution {
2 public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
3 ListNode prev = list1;
4 for (int i = 0; i < a - 1; i++) {
5 prev = prev.next;
6 }
7 ListNode after = prev;
8 for (int i = 0; i < b - a + 2; i++) {
9 after = after.next;
10 }
11 prev.next = list2;
12 ListNode tail = list2;
13 while (tail.next != null) {
14 tail = tail.next;
15 }
16 tail.next = after;
17 return list1;
18 }
19}1class Solution {
2public:
3 ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
4 ListNode* prev = list1;
5 for (int i = 0; i < a - 1; i++) {
6 prev = prev->next;
7 }
8 ListNode* after = prev;
9 for (int i = 0; i < b - a + 2; i++) {
10 after = after->next;
11 }
12 prev->next = list2;
13 ListNode* tail = list2;
14 while (tail->next) {
15 tail = tail->next;
16 }
17 tail->next = after;
18 return list1;
19 }
20};Time and space complexity
O(n + m)
We walk at most b + 1 nodes of list1 and every node of list2 once.
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
afteron node b instead of node b + 1. Then the last removed node stays in the list. - Walking
preva steps instead of a - 1, which lands on the first node to remove instead of the one before it. - Rewiring
prev.nextbefore findingafterwhile also walkingafterfromprev.next. Onceprev.nextpoints at list2, that walk goes into the wrong list. - Forgetting to walk to list2's tail and linking list2's head to
afterinstead, 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.