Python 1669.py
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
# scan forward to the "red zone"
one = list1
for _ in range(a - 1):
one = one.next
# find end of "red zone"
two = one
for _ in range(b + 1 - (a - 1)):
two = two.next
# add list2 to first half of list1
one.next = list2
while one.next:
one = one.next
# add second half of list1
one.next = two
return list1
Difficulty
and has an acceptance rate of about 82% (200k+ submissions).
Typical patterns to solve this problem:
- Linked List
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation merges a second singly-linked list (list2) into a first list (list1) by replacing the segment of list1 that starts at index a and ends at index b. The algorithm walks the first list only as far as necessary to locate the insertion points, splices list2 in place, and then reconnects the tail of list1 that follows the removed segment. All operations are performed by adjusting the next pointers of existing nodes, avoiding any allocation of new list nodes.
Scanning to the node before the removal segment
The first loop advances a pointer (one) from the head of list1 to the node that precedes the segment to be removed. The loop iterates a-1 times, which positions one exactly at the node whose next will become the head of list2.
one = list1
for _ in range(a - 1):
one = one.next
When a equals 0, the range evaluates to an empty sequence, leaving one at the head of list1. This implicitly handles the edge case where the removal segment starts at the very beginning of the list.
Locating the node after the removal segment
A second pointer (two) is initialized to the same node as one. The following loop moves two forward enough steps to land on the node that follows the segment ending at index b. The number of steps is calculated as b + 1 - (a - 1), which simplifies to b - a + 2.
two = one
for _ in range(b + 1 - (a - 1)):
two = two.next
If b points to the last node of list1, the loop advances two until it becomes None. The code therefore gracefully handles the situation where the removal segment includes the tail of the list.
Splicing the second list into the first
The next statement connects the node before the removal segment (one) directly to the head of list2.
one.next = list2
If list2 is None, this assignment effectively removes the segment without inserting any new nodes, demonstrating correct handling of an empty second list.
Advancing to the end of the inserted segment
After linking list2, the algorithm walks forward from one until it reaches the final node of the inserted segment. The loop continues while one.next is not None, thereby stopping at the last node of list2 (or at one itself if list2 was empty).
while one.next:
one = one.next
Because the traversal stops as soon as the end of list2 is found, no unnecessary passes over the list are performed.
Reconnecting the remaining part of the first list
Finally, the node that now sits at the end of the inserted segment (one) is linked to the node that follows the removed segment (two). This restores the continuity of the combined list.
one.next = two
If two is None, the assignment correctly terminates the merged list at the end of list2.
Return value
The method returns the head of the modified list1, which now represents the merged list.
return list1
Edge-case handling
The code implicitly supports several boundary conditions without additional checks. When the removal segment starts at the head (a == 0), the initial loop does not move the pointer, and the head of list1 is directly replaced by list2. When the removal segment includes the last node (b points to the tail), the second loop advances two to None, and the final connection correctly terminates the list. An empty list2 results in a simple excision of the specified segment, as the assignment one.next = list2 sets the link to None and the subsequent while-loop does not iterate.
Performance considerations
The algorithm performs a single forward traversal for each of the three distinct phases: locating the insertion point before the segment, locating the node after the segment, and walking to the end of list2. Each traversal touches only the necessary nodes, avoiding repeated passes over the same portion of the list. By reusing existing node references and never allocating auxiliary data structures, the implementation minimizes memory overhead and leverages the inherent O(1) pointer manipulation cost of singly-linked lists. The use of simple for loops with known iteration counts ensures predictable iteration patterns, which can be beneficial for CPU branch prediction and cache utilization.
ELI5 - Simplified Explanation
Imagine a long train made of many little cars linked together by shiny hooks. Each car is a piece of data. There is a big train called list1 and a smaller train called list2. The goal is to take a section out of the middle of the big train and put the entire smaller train in that empty spot.
First, the code travels along the big train to find the exact car just before the part that needs to be removed. It stops there and saves that spot. Next, it keeps moving forward to find the car that comes right after the part that should be thrown away. It saves that spot too.
Now it is time to connect the pieces like a puzzle. One end of the big train gets attached to the front of the small train. Then, it walks all the way through the small train until it reaches the very last car. Finally, it links that last car of the small train to the piece of the big train that it saved earlier. Now the big train is back together with a shiny new middle section.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | Python | C++ | Java | TS | ||||
| WalkCCC | Python | C++ | Java | ||||||
| leetcode.ca | Python | C++ | Java | C# | Go | TS | |||
| Progiez | Python | C++ | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1360: Number of Days Between Two Dates
- problem 1576: Replace All ?'s to Avoid Consecutive Repeating Characters
- problem 1716: Calculate Money in Leetcode Bank
- problem 2409: Count Days Spent Together
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2644: Find the Maximum Divisibility Score
- problem 1110: Delete Nodes And Return Forest
- problem 1296: Divide Array in Sets of K Consecutive Numbers
- problem 1443: Minimum Time to Collect All Apples in a Tree
- problem 458: Poor Pigs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality