Advertisement

Merge In Between Linked Lists - LeetCode 1669 Solution

Merge In Between Linked Lists - Complete Solution Guide

Merge In Between Linked Lists is LeetCode problem 1669, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1 's nodes from the a th node to the b th node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head. 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: We remove the nodes 3 and 4 and put the entire list2 in their place. Th

Detailed Explanation

The problem asks us to modify `list1` by removing a sublist of nodes from index `a` to `b` (inclusive) and replacing it with `list2`. We need to return the modified `list1`. Specifically, the node at index `a-1` in `list1` should point to the head of `list2`, and the tail of `list2` should point to the node that originally followed index `b` in `list1`.

Solution Approach

The solution involves traversing `list1` to locate the node before the start of the sublist to be removed (`a-1`) and the node after the end of the sublist to be removed (`b+1`). Then, it connects the node at `a-1` to the head of `list2` and finds the tail of `list2`. Finally, it connects the tail of `list2` to the node originally at `b+1` in `list1`. This effectively splices `list2` into `list1` in place of the removed sublist.

Step-by-Step Algorithm

  1. Step 1: Traverse `list1` from the head to the node at index `a-1`. This is done using a loop that iterates `a-1` times.
  2. Step 2: Traverse `list1` from the node at `a-1` to the node at index `b`. Note that the code advances the pointer `b-a+1` times from the `a-1` node, effectively reaching the node indexed at `b`.
  3. Step 3: Set the `next` pointer of the node at index `a-1` to point to the head of `list2`.
  4. Step 4: Traverse `list2` to find its tail (the last node). This is done using a loop that continues until the `next` pointer is `None`.
  5. Step 5: Set the `next` pointer of the tail of `list2` to point to the node that originally followed index `b` in `list1` (the node initially after `node_b`).
  6. Step 6: Return the head of the modified `list1`.

Key Insights

  • Insight 1: We need to traverse `list1` to find the nodes at indices `a-1` and `b`.
  • Insight 2: We need to find the tail of `list2` to connect it to the remaining part of `list1`.
  • Insight 3: We need to handle the connections correctly to avoid breaking the list or creating cycles.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Linked List.

Companies

Asked at: Arista Networks, PayPal.