Reverse Linked List II - Problem
Reverse Linked List II is a classic linked list manipulation problem that tests your ability to work with pointers and maintain proper connections.
You're given the
For example, if you have the list
This problem requires careful pointer manipulation to avoid breaking the list connections during the reversal process.
You're given the
head of a singly linked list and two integers left and right where left ≤ right. Your task is to reverse only the nodes from position left to position right (1-indexed), while keeping the rest of the list intact.For example, if you have the list
1→2→3→4→5 and need to reverse from position 2 to 4, the result should be 1→4→3→2→5. Notice how only the middle section gets reversed while the surrounding nodes remain in their original positions.This problem requires careful pointer manipulation to avoid breaking the list connections during the reversal process.
Input & Output
example_1.py — Basic Reversal
$
Input:
head = [1,2,3,4,5], left = 2, right = 4
›
Output:
[1,4,3,2,5]
💡 Note:
We reverse the sublist from position 2 to 4. The nodes 2→3→4 become 4→3→2, while positions 1 and 5 remain unchanged.
example_2.py — Single Node Reversal
$
Input:
head = [5], left = 1, right = 1
›
Output:
[5]
💡 Note:
When left equals right, we're reversing a single node, so the list remains unchanged.
example_3.py — Reverse Entire List
$
Input:
head = [3,5], left = 1, right = 2
›
Output:
[5,3]
💡 Note:
When we reverse from position 1 to the last position, we effectively reverse the entire linked list.
Constraints
-
The number of nodes in the list is
n -
1 ≤ n ≤ 500 -
-500 ≤ Node.val ≤ 500 -
1 ≤ left ≤ right ≤ n - Follow up: Could you do it in one pass?
Visualization
Tap to expand
Understanding the Visualization
1
Position the Conductor
Find the car just before the section to reverse (like finding prevLeft node)
2
Disconnect and Reverse
Carefully disconnect cars in the target section and reverse their order using coupling manipulation
3
Reconnect the Train
Attach the reversed section back to both ends of the original train to complete the operation
Key Takeaway
🎯 Key Insight: The optimal approach treats the problem like a train conductor carefully rearranging cars - find the right position, reverse the middle section using pointer manipulation, then reconnect everything without losing any connections!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code