Merge In Between Linked Lists - Java Solution (Beats 100%)
Intuition\n Describe your first thoughts on how to solve this problem. \nMy intuition involves identifying the nodes aPrev and bNext in list1, representing the 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy intuition involves identifying the nodes aPrev and bNext in list1, representing the positions before and after the removal range, and finding the last node of list2. By connecting aPrev to the head of list2 and the last node of list2 to bNext seamlessly replace the specified range in list1 with list2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s break down my approach for solution step by step:\n- **Finding the Node aPrev:** Start by iterating through the list1 until you reach the (a-1)th node, which is the node just before the range you want to remove.\n\n- **Finding the Node bNext:** Similarly, iterate through the list1 until you reach the (b+1)th node, which is the node just after the range you want to remove.\n\n- **Finding the Last Node of list2:** Iterate through list2 to find its last node. This is important for connecting list2 to the remaining part of list1 after removal.\n\n- **Connecting list2 to list1:** After finding aPrev, bNext, and the last node of list2, set aPrev.next to point to the head of list2, effectively connecting the part before the removal range to list2.\nThen, set the next of the last node in list2 to point to bNext, linking the remaining part of list1 after the removal range.\n\nAt last return the head of modified list1.\n# Complexity\n- **Time complexity:** The time complexity of my code is **O(n + m)**, where n is the size of list1, and m is the size of list2. O(n + m) is equivalent to O(n).\n\n- **Space complexity:** The space complexity is **O(1)** as we use a constant amount of extra space to store variables like aPrev, bNext, and temp.\n# Code\n```\nclass Solution {\n    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n        ListNode aPrev = list1;\n        int i = 0;\n        while (i < a-1) {\n            aPrev = aPrev.next;\n            i++;\n        }\n        ListNode bNext = list1;\n        int j = 0;\n        while (j <= b) {\n            bNext = bNext.next;\n            j++;\n        }\n\n        ListNode temp = list2;\n        while (temp.next != null) {\n            temp = temp.next;\n        }\n\n        aPrev.next = list2;\n        temp.next = bNext;\n\n        return list1;\n    }\n}\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNode() {}\n *     ListNode(int val) { this.val = val; }\n *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\n```
['Java']