Merge In Between Linked Lists - 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.

Build the result list and return its head.

Input & Output

Example 1 — Basic Replacement
$ Input: list1 = [0,1,2,3,4], a = 1, b = 3, list2 = [1000000,1000001,1000002]
Output: [0,1000000,1000001,1000002,4]
💡 Note: Remove nodes from index 1 to 3 (values 1,2,3) and replace with list2. Keep node 0 and node 4, insert list2 in between.
Example 2 — Single Node Replacement
$ Input: list1 = [0,1,2,3,4], a = 3, b = 3, list2 = [1000000,1000001]
Output: [0,1,2,1000000,1000001,4]
💡 Note: Remove only the node at index 3 (value 3) and replace with list2. Result keeps 0,1,2, inserts list2, then keeps 4.
Example 3 — Edge Case at End
$ Input: list1 = [0,1,2], a = 1, b = 2, list2 = [5,6,7]
Output: [0,5,6,7]
💡 Note: Remove nodes 1 and 2 from the end, replace with list2. Only node 0 remains from original list.

Constraints

  • 3 ≤ list1.length ≤ 104
  • 1 ≤ a ≤ b < list1.length - 1
  • 1 ≤ list2.length ≤ 104
  • 1 ≤ list1[i], list2[i] ≤ 106

Visualization

Tap to expand
Merge In Between Linked ListsInput: list1 = [0,1,2,3,4], a=1, b=301234keepremove a=1 to b=3keeplist2 = [A,B,C]ABCResult after merging:0ABC4Output: [0,A,B,C,4]
Understanding the Visualization
1
Input Lists
list1=[0,1,2,3,4], a=1, b=3, list2=[A,B,C]
2
Identify Segment
Remove nodes from index a to b (inclusive)
3
Insert Replacement
Splice list2 into the gap where removed nodes were
Key Takeaway
🎯 Key Insight: Use direct pointer manipulation to reconnect the list segments without extra space
Asked in
Microsoft 35 Amazon 28 Google 22
32.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen