Reverse Nodes in k-Group
Master this topic with zero to advance depth.
Reverse Nodes in k-Group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
List: 1 -> 2 -> 3 -> 4 -> 5, k = 3
1. Group [1,2,3] -> Reverse -> 3 -> 2 -> 1
2. Group [4,5] (Size 2 < 3) -> Keep 4 -> 5
Result: 3 -> 2 -> 1 -> 4 -> 5Examples
The list is reversed in groups of size 2.
Level I: Recursive Approach
Intuition
We can solve the problem recursively by reversing the first k nodes and then calling the function recursively for the rest of the list.
Detailed Dry Run
List: 1->2->3->4->5, k=2.
- First 2 nodes: 1->2. Reverse: 2->1.
- Recursive call on 3->4->5.
- Link 1 to the result of recursive call.
⚠️ Common Pitfalls & Tips
O(N/k) recursion stack space is used. The last group with < k nodes must be left as is.
Level II: Iterative with Stack
Intuition
Traverse the list and push k nodes onto a stack. If we have k nodes, pop them to reverse. If we reach the end with fewer than k nodes, append them as is.
Visual Trace
List: 1 -> 2 -> 3 -> 4, k=2
Iter 1: Stack=[1, 2]. Pop: 2 -> 1
Iter 2: Stack=[3, 4]. Pop: 4 -> 3
Result: 2 -> 1 -> 4 -> 3Detailed Dry Run
List: 1->2->3, k=2. Stack=[1, 2], pop to get 2->1. Append 3.
Level III: Optimal (Iterative Constant Space)
Intuition
To achieve O(1) space, we can iterate through the list and reverse the nodes in-place group by group. We use a dummy node to handle the head of the list properly.
Detailed Dry Run
Dummy -> 1 -> 2 -> 3 -> 4 -> 5, k=2.
- Reverse 1, 2: Dummy -> 2 -> 1 -> 3.
- Next group 3, 4: Dummy -> 2 -> 1 -> 4 -> 3 -> 5.
⚠️ Common Pitfalls & Tips
Careful with pointer manipulations. Ensure the count check correctly stops when fewer than k nodes remain.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.