#1669
Merge In Between Linked Lists
MediumLinked ListLinked ListTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
This approach directly modifies the links in list1 to insert list2 in place of the nodes to be removed. It is efficient because it only requires a single pass through the relevant parts of the lists.
⚙️
Algorithm
4 steps- 1Step 1: Create a dummy node to simplify edge cases and point it to list1.
- 2Step 2: Traverse to the (a-1)th node and keep a reference to it.
- 3Step 3: Traverse to the (b+1)th node to find the node after the section to remove.
- 4Step 4: Connect the (a-1)th node's next to list2, and the last node of list2 to the (b+1)th node.
solution.py20 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def mergeInBetween(list1, a, b, list2):
8 dummy = ListNode(0)
9 dummy.next = list1
10 prev = dummy
11 for _ in range(a):
12 prev = prev.next
13 curr = prev.next
14 for _ in range(b - a + 1):
15 curr = curr.next
16 prev.next = list2
17 while list2.next:
18 list2 = list2.next
19 list2.next = curr
20 return dummy.nextℹ
Complexity note: This complexity is linear because we only traverse the relevant parts of the lists once, making it efficient.
- 1Understanding linked list manipulation is crucial.
- 2Identifying the nodes to connect is key to solving this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.