Problem 1669

Abstract / Summary

Insert one linked list between two nodes of another linked list by adjusting pointers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
20 lines | 567 bytes | submitted December 6, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (200k+ submissions).

Typical patterns to solve this problem:
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.41 | σ = 1.37

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
29 links | 17 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   December 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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