Java Solution O(n) Complexity Beats 100% in Runtime
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem here is to traverse through the linked list to find the a\'th and b\'
![Screenshot 2024-03-20 143610.png](https://assets.leetcode.com/users/images/7bf9de4d-e670-401e-a401-089854237b57_1710925626.221034.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem here is to traverse through the linked list to find the a\'th and b\'th nodes. Then remove list1\'s nodes from a to b and replace it with l2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- We begin by declaring to temporary nodes node1 and node2 which help us to find the ath and bth node respectively.\n- Using a for loop we traverse from 1 to b (we will find positions of node1 and node2 using 1 loop itself). Since a<=b we iterate from 1 to b.\n- Till we reach b update node2 to point to its next element by `node2=node2.next;` and also check if the current value of i in the loop is lesser than a (We need to find the node before the ath node that\'s why we check for lesser than not lesser than or equal to.)\n- If true then update node1 to point to its next elemnt by `node1=node1.next`.\n- Now we have node1 pointing to node before the ath element and node2 pointing to bth element.\n- To remove the nodes we simply make node1.next to point to first element of list2 by  `node1.next=list2`.\n- Now to make the last item of list2 to point to b+1th node in list1 we simply use node1 iteself and travese using a while loop untill node1.next is not null (Find the last node in list2).\n- Now we use node1 to point to b+1 th element in the list by `node1.next=node2.next` (as node2 is pointing to bth node).\n- Finally we disconnect the bth node by making its next as null by `node2.next=null`\n- Return the head of list1 by `return list1`\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\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 */\nclass Solution {\n    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n        ListNode node1 = list1;\n        ListNode node2 = list1;\n        for(int i=1;i<=b;i++){\n            node2 = node2.next;\n            if(i<a)\n            node1 = node1.next;\n        }\n        node1.next = list2;\n        while(node1.next!=null)node1=node1.next;\n        node1.next = node2.next;\n        node2.next = null;\n        return list1;\n    \n    }\n}\n```
['Linked List', 'Java']