AlgoInsight

DSA problem

Merge In Between Linked Lists

MediumLinked ListPattern: Linked Listtop600AmazonMicrosoftGoogleAdobeApple

You are given two linked lists, list1 and list2, along with two integer indices a and b. Your task is to remove the nodes of list1 from position a to position b inclusive, and splice the entire list2 into that gap, then return the head of the resulting combined list.

Conceptually you need three reference points in list1: the node just before position a (call it the prefix tail), the node at position b (the last node to be removed), and the node just after position b (the suffix head). Once you have these, the rewiring is straightforward: connect the prefix tail to the head of list2, and connect the tail of list2 to the suffix head.

The constraints guarantee 1 <= a <= b, so the node before position a always exists — you never have to deal with removing the head of list1. That keeps the logic clean and avoids any dummy-node bookkeeping.

The optimal approach is a single linear scan. Walk list1 to find the node at index a - 1 and the node at index b + 1 (or null if b is the last index). Then walk list2 to its tail. Finally perform two pointer assignments to stitch everything together. This runs in O(m + k) time, where m is the length of list1 and k the length of list2, using O(1) extra space.

Examples

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: Nodes at indices 3 and 4 (values 6 and 9) are removed, and list2 is spliced in their place between value 13 and value 5.
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: Nodes at indices 2 through 5 (values 2,3,4,5) are removed, and the whole of list2 is inserted between value 1 and value 6.
Example 3
Input: list1 = [0,1,2], a = 1, b = 1, list2 = [9,9]
Output: [0,9,9,2]
Explanation: Only the node at index 1 (value 1) is removed, and list2 = [9,9] is spliced between value 0 and value 2.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-list

Browse all DSA problems