Introduction
Reverse Linked List II means reversing only a specific portion of a linked list.
The task is to:
- reverse nodes from left to right position
- keep remaining nodes unchanged
- reconnect reversed portion correctly
Example:
Input:1 -> 2 -> 3 -> 4 -> 5
left = 2
right = 4
Output:
1 -> 4 -> 3 -> 2 -> 5
Explanation:
Nodes between 2 and 4 are reversed.Remaining nodes stay unchanged.This problem is one of the most important applications of:
Pointer ManipulationConstraints
1 <= Number of Nodes <= 10^51 <= left <= right <= n
Approach 1 : Brute Force (Using Array)
Explanations:
Explanation:
The idea is:
- store linked list values in array
- reverse subarray
- rebuild linked list
Steps:
- Traverse linked list.
- Store node values.
- Reverse selected portion.
- Create updated linked list.
This approach works but:
- uses extra memory
So in-place reversal is preferred.
Dry Run
Input:1 -> 2 -> 3 -> 4 -> 5
left = 2
right = 4
Array:
[1,2,3,4,5]
Reverse:
[2,3,4]
Updated:
[1,4,3,2,5]
Output:
1 -> 4 -> 3 -> 2 -> 5
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :
Linked list traversal takes linear time.
Space Complexity:- O(n)
Explanation :
Extra array is used.
Approach 2 : Optimal Solution(Using Pointer Reversal)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- reach left position
- reverse links until right position
- reconnect remaining nodes
This performs reversal in-place.
Dry Run
Input:1 -> 2 -> 3 -> 4 -> 5
left = 2
right = 4
Reverse:
2 -> 3 -> 4
Becomes:
4 -> 3 -> 2
Reconnect:
1 -> 4 -> 3 -> 2 -> 5
Practice :