Leetcode 1669: Merge In Between Linked Lists

grid47
grid47
Exploring patterns and algorithms
May 24, 2024 5 min read

You are given two linked lists: list1 and list2 with sizes n and m respectively. The task is to remove the nodes from position a to position b in list1 and replace them with list2. Return the head of the modified list.
Problem
Approach
Steps
Complexity
Input: You are given two linked lists, `list1` and `list2`, along with indices `a` and `b` which define the range of nodes to be removed from `list1`.
Example: list1 = [5,3,9,7,2,8], a = 2, b = 3, list2 = [100,200,300]
Constraints:
• 3 <= list1.length <= 104
• 1 <= a <= b < list1.length - 1
• 1 <= list2.length <= 104
Output: Return the head of the modified list after replacing the specified nodes in `list1` with `list2`.
Example: [5,3,100,200,300,2,8]
Constraints:
• The returned list should reflect the changes made.
Goal: To modify `list1` by removing the specified nodes and inserting `list2` in their place.
Steps:
• Identify the nodes in `list1` at positions `a` and `b`.
• Remove the nodes between positions `a` and `b` in `list1`.
• Link the previous part of `list1` to the first node of `list2`.
• Link the last node of `list2` to the remainder of `list1`.
Goal: The list lengths and node positions must be within the given bounds.
Steps:
• 1 <= a <= b < list1.length - 1
• list2 length is between 1 and 104
• list1 length is between 3 and 104
Assumptions:
• The linked list is non-empty, and the indices `a` and `b` are within the valid range.
Input: list1 = [5,3,9,7,2,8], a = 2, b = 3, list2 = [100,200,300]
Explanation: We remove the nodes at positions 2 and 3 (`9` and `7`) and insert the list `[100,200,300]` in their place.

Input: list1 = [0,2,4,6,8,10], a = 1, b = 3, list2 = [500,600,700]
Explanation: The nodes at positions 1, 2, and 3 (`2`, `4`, and `6`) are removed, and `[500,600,700]` is inserted in their place.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus