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 Lists INPUT list1: 0 1 2 3 4 idx:0 a=1 b=3 idx:4 = To be removed list2: 1000000 1000001 1000002 Input Values: list1 = [0,1,2,3,4] a = 1 b = 3 list2 = [1000000, 1000001,1000002] ALGORITHM STEPS 1 Find node before 'a' Traverse to index (a-1) ptr1 points to node[0] 2 Find node after 'b' Traverse to index (b+1) ptr2 points to node[4] 3 Connect ptr1 to list2 ptr1.next = list2.head node[0].next = 1000000 4 Connect list2 tail to ptr2 Find list2 end, link ptr2 1000002.next = node[4] Pointer Manipulation: 0 list2 4 Red arrows = new connections FINAL RESULT Merged Linked List: 0 1000000 1000001 1000002 4 NULL Output: [0,1000000,1000001, 1000002,4] OK - Merged! Complexity: Time: O(n+m) | Space: O(1) Key Insight: Direct pointer manipulation allows O(1) space complexity. We only need to find two critical points: the node before 'a' (to attach list2's head) and the node after 'b' (to attach to list2's tail). The removed nodes (indices a to b) are simply bypassed by rewiring the next pointers. TutorialsPoint - Merge In Between Linked Lists | Direct Pointer Manipulation Approach
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