LeetCode 1669: Merge In Between Linked Lists Solution

Master LeetCode problem 1669 (Merge In Between Linked Lists), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1669. Merge In Between Linked Lists

Problem Explanation

Explanation:

To solve this problem, we need to remove nodes from the ath to bth positions in list1 and replace them with the nodes from list2. We can achieve this by first finding the nodes at positions a-1 and b in list1, then adjust the pointers accordingly to connect the nodes from list2.

  1. Traverse list1 to find the (a-1)th node and bth node.
  2. Connect the (a-1)th node to the head of list2 and the last node of list2 to the bth node.
  3. Update the head of list1 if a=1.
  4. Return the head of the modified list1.

Time complexity: O(n + m) where n is the size of list1 and m is the size of list2. Space complexity: O(1)

:

Solution Code

class Solution {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode dummy = new ListNode(0);
        dummy.next = list1;
        ListNode prevA = dummy;
        
        for (int i = 0; i < a - 1; i++) {
            prevA = prevA.next;
        }
        
        ListNode nodeB = prevA;
        for (int i = 0; i < b - a + 2; i++) {
            nodeB = nodeB.next;
        }
        
        prevA.next = list2;
        while (list2.next != null) {
            list2 = list2.next;
        }
        list2.next = nodeB;
        
        return dummy.next;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1669 (Merge In Between Linked Lists)?

This page provides optimized solutions for LeetCode problem 1669 (Merge In Between Linked Lists) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1669 (Merge In Between Linked Lists)?

The time complexity for LeetCode 1669 (Merge In Between Linked Lists) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1669 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1669 in Java, C++, or Python.

Back to LeetCode Solutions