Coding Interview PatternsReverse Nodes in k-Group
HardIn-Place Manipulation of a Linked List
Reverse Nodes in k-Group
Explanation & Solution
Description
Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then the remaining nodes at the end should remain as-is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Input:head = [1,2,3,4,5], k = 2
0
1
1
2
2
3
3
4
4
5
Output:[2,1,4,3,5]
0
2
1
1
2
4
3
3
4
5
Explanation: Reverse in groups of 2: [1,2] becomes [2,1], [3,4] becomes [4,3], and [5] stays.
Constraints
- The number of nodes in the list is
n 1 <= k <= n <= 50000 <= Node.val <= 1000
Approach
In-Place Manipulation of a Linked List pattern
1. Create a Dummy Node
- Create a
dummynode beforeheadto simplify pointer updates. groupPrevtracks the node right before the current group to reverse.
2. Find the k-th Node
- From
groupPrev, advanceksteps to findkth. - If we can't advance
ktimes (fewer remaining nodes), we're done — leave the remaining nodes as-is.
3. Reverse the Current Group
- Save
groupNext = kth.next(the node after the group). - Set
prev = groupNextso the reversed group's tail connects to the rest of the list. - Reverse
knodes by iterating and flipping pointers.
4. Reconnect and Advance
- After reversal,
prevpoints to the new front of the group (waskth). groupPrev.next = prevconnects the previous part to the reversed group.- Move
groupPrevtotail(the original first node, now the last in the reversed group). - Repeat for the next group.
🧠 Key Insight
- The key is checking whether
knodes remain before attempting reversal. - Each group reversal is just the standard linked list reversal applied to a sublist.
Time
O(n)each node is visited at most twice (once to count, once to reverse).Space
O(1)only pointer variables are used.Visualization
Input:
Linked List Traversal
—
Press play to start traversal
Slow (S)Fast (F)Both
4 steps