Merge In Between Linked Lists Problem
#1669
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1669.
You are given two linked lists: list1 and list2 of sizes n and m respectively.
Remove list1's nodes from the a^th node to the b^th node, and put list2 in their place.
The blue edges and nodes in the following figure indicate the result:

Build the result list and return its head.
Example 1:

Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [10,1,13,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
Example 2:

Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]
Explanation: The blue edges and nodes in the above figure indicate the result.
Constraints:
3 <= list1.length <= 10^41 <= a <= b < list1.length - 11 <= list2.length <= 10^4
Solution
Approach: Find the Two Cut Points
We only need two nodes of list1:
p, the node just before thea-th node (it isa - 1steps from the head), andq, theb-th node itself (bsteps from the head).
Point p.next at the head of list2, walk to the last node of list2, and point its next at q.next. Setting q.next = None cuts the removed part off. The head of list1 never changes because a >= 1.
Complexity: O(n + m) time, where n and m are the lengths of list1 and list2, and O(1) extra space.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(
self, list1: ListNode, a: int, b: int, list2: ListNode
) -> ListNode:
p = q = list1
for _ in range(a - 1):
p = p.next
for _ in range(b):
q = q.next
p.next = list2
while p.next:
p = p.next
p.next = q.next
q.next = None
return list1