Coding Interview PatternsReverse Linked List II
MediumIn-Place Manipulation of a Linked List
Reverse Linked List II
Explanation & Solution
Description
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Input:head = [1,2,3,4,5], left = 2, right = 4
0
1
1
2
2
3
3
4
4
5
Output:[1,4,3,2,5]
0
1
1
4
2
3
3
2
4
5
Explanation: Nodes at positions 2 through 4 (values 2,3,4) are reversed to (4,3,2).
Constraints
- The number of nodes in the list is
n 1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
Approach
In-Place Manipulation of a Linked List pattern
1. Create a Dummy Node
- Create a
dummynode pointing toheadto handle the edge case whereleft = 1(reversing from the head). - Move
prevto the node just before positionleft.
2. Position the Pointers
- Traverse
left - 1steps soprevis right before the reversal zone. - Set
currtoprev.next— this is the first node in the sublist to reverse.
3. Reverse the Sublist
- Iterate
right - lefttimes. In each iteration: - Save
next = curr.next(the node to be moved to the front). - Remove
nextfrom its position:curr.next = next.next. - Insert
nextat the front of the reversed portion:next.next = prev.next. - Update the connection:
prev.next = next. - After each iteration, one more node has been moved to the front of the sublist.
4. Return the Result
dummy.nextis the new head (it may have changed ifleft = 1).- Collect values and return as an array.
🧠 Key Insight
- The "pull node to front" technique avoids explicitly tracking the tail of the reversed sublist.
- The dummy node eliminates special-casing the head.
Time
O(n)single pass through the list.Space
O(1)only pointer variables used.Visualization
Input:
Linked List Traversal
—
No animation available
Slow (S)Fast (F)Both
0 steps