Merge In Between Linked Lists — LeetCode 1669 Python Solution
- Problem
- #1669
- Pattern
- Linked List
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1's nodes from the ath node to the bth node, and put list2 in their place.
Example
- 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.
Python solution
# 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 list1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(1) auxiliary |
Pattern: Linked List
Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 1669. Merge In Between Linked Lists is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.
The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1669. Merge In Between Linked Lists?
- LeetCode 1669. Merge In Between Linked Lists is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1669. Merge In Between Linked Lists?
- The Python solution on this page runs in O(m + n).
- What is the space complexity of LeetCode 1669. Merge In Between Linked Lists?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1669. Merge In Between Linked Lists cover?
- LeetCode 1669. Merge In Between Linked Lists is tagged Linked List on LeetCode.