Introduction
Reverse Nodes in K Group means reversing linked list nodes in groups of size k.
The task is to:
- divide linked list into groups
- reverse every k nodes
- maintain remaining links correctly
Example:
Input:1 -> 2 -> 3 -> 4 -> 5
k = 2
Output:
2 -> 1 -> 4 -> 3 -> 5
Explanation:
First group:
1 -> 2
Becomes:
2 -> 1
Second group:
3 -> 4
Becomes:4 -> 3
This problem is one of the most important applications of:
Pointer Manipulation Constraints
1 <= Number of Nodes <= 10^5
1 <= k <= nApproach 1 : Brute Force (Using Array)
Explanations:
Explanation:
The idea is:
- store linked list values in array
- reverse every k sized group
- rebuild linked list
Steps:
- Traverse linked list.
- Store node values.
- Reverse every k elements.
- 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
k = 2
Array:
[1,2,3,4,5]
Reverse groups:
[2,1,4,3,5]
Output:
2 -> 1 -> 4 -> 3 -> 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:
- reverse nodes group by group
- reconnect groups correctly
- perform reversal in-place
This avoids extra memory usage.
Dry Run
Input:1 -> 2 -> 3 -> 4 -> 5
k = 2
Group 1:
1 -> 2
Becomes:
2 -> 1
Group 2:
3 -> 4
Becomes:
4 -> 3
Final:
2 -> 1 -> 4 -> 3 -> 5
Practice :