Reverse K-Groups
Reverse every K consecutive nodes. Check if K nodes remain, reverse them, connect to the result of recursively processing the rest. If fewer than K nodes remain, leave them as-is.
How It Works
Reverse Nodes in k-Group applies full-list reversal to consecutive blocks of exactly k nodes, leaving any final short block untouched. For each block: first walk ahead to confirm k nodes remain — if not, stop. Then reverse those k nodes with the standard prev/curr loop, and splice the block back in: the previous block's tail connects to this block's new front, and this block's new tail (its original first node) connects to whatever follows. A dummy node again supplies a uniform predecessor for the first block.
Every node is visited a constant number of times (one check pass, one reversal pass), so the total is O(n) time. Iteratively it is O(1) space; the recursive formulation trades that for O(n/k) stack frames of cleaner code.
Step-by-Step Visualization
Code
static ListNode reverseKGroup(ListNode head, int k) {
int count = 0;
ListNode curr = head;
while (curr != null && count < k) { curr = curr.next; count++; }
if (count < k) return head;
ListNode prev = null;
curr = head;
for (int i = 0; i < k; i++) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head.next = reverseKGroup(curr, k);
return prev;
}Tips & Gotchas
Practice Problems
- 1Reverse Nodes in k-Group
- 2Swap Nodes in Pairs
- 3Reverse Linked List II
About the In-Place Reversal Pattern
Reverse the direction of pointers one by one. Use three pointers: prev, current, and next. Save next, point current back to prev, then advance prev and current. After the loop, prev is the new head.
Most linked list problems are about pointer manipulation. Draw it out! Fast & slow pointers detect cycles and find midpoints. In-place reversal is the other core technique.
Common Linked List Interview Problems
- Reverse Linked List
- Merge Two Sorted Lists
- Linked List Cycle
- Remove Nth Node From End
- LRU Cache
- Reorder List
Frequently Asked Questions
Why check for k remaining nodes before reversing?
The problem requires a trailing group of fewer than k nodes to keep its original order. Reversing first and undoing on failure is wasted, bug-prone work; a quick k-step lookahead costs O(k) and keeps the reversal unconditional. The check is also the natural recursion base case.
How does Swap Nodes in Pairs relate to this problem?
It is exactly k-group reversal with k = 2, which is why solving pairs first is good practice. The pair version is simple enough to write with direct pointer swaps, but the general k version forces the full pattern: check, reverse, splice, advance.