Reverse Nodes in k-Group
Reverse Nodes in k-Group is LeetCode 25 (Hard). Split a linked list into blocks of k nodes from the front, reverse the order of the nodes inside every full block, and return the new head.
- If the last block has fewer than
knodes, it stays exactly as it is. - Only links may change, not the values stored in the nodes.
- The follow-up asks for O(1) extra memory, which rules out a stack per block and deep recursion.
- The number of nodes in the list is n.
- 1 <= k <= n <= 5000
- 0 <= Node.val <= 1000
Intuition
Reversing one stretch of a list is the loop from Reverse Linked List. The new work is at the seams. Each block has a node in front of it (before) and a node after it (after), and both must be wired to the block's new ends.
- Start the reversal at
after, not at null. The block's first node is the first one turned, so it ends up pointing atafterwith no extra step. - Then fix the front.
beforestill points at the old first node; point it at the old last node instead. The old first node is now the block's end, so it becomesbeforefor the next block.
A placeholder in front of the head gives the first block a before too.
"Reverse every k nodes", "swap nodes in pairs" (k = 2) and "reverse between positions" are all one reversal loop plus careful reconnection at the block edges.
Approach
Before reading on, take [1, 2, 3, 4, 5] with k = 2 and write down, after the first block is reversed, which node each of the placeholder, 1 and 2 points to. Then decide which node plays the placeholder's role for the second block.
Loop or recursion
Walks the list once, reversing each full block and rewiring its two seams.
- Meets the follow-up: a handful of pointers.
- More bookkeeping:
before,kthandaftermust be kept straight.
The answer to aim for.
Solves the rest of the list first, then reverses the current block onto that result.
- Fewer pointers: no placeholder, no
before. - Stack grows: one call per block, 5000 calls when
k = 1.
The usual first idea.
Both touch each node a constant number of times. The loop is traced below; the recursive version follows the demo.
Put a placeholder before the head
Create dummy pointing at head and set before = dummy. The first block's front then needs the same rewiring as every other block, and dummy.next always holds the current head.
Check that k nodes are left
Walk k steps from before to reach kth, the block's last node. If the walk hits null first, fewer than k nodes remain, so return dummy.next and leave them alone. Checking before any change is what keeps the short tail untouched.
Reverse the block toward the node after it
Let after = kth.next. Run the usual reversal loop from before.next until reaching after, but start the backward-pointing chain at after instead of null. The block's first node now points to after, so the back seam is already joined.
Join the front and move on
Remember first = before.next (the old first node), set before.next = kth, then set before = first. The old first node is the block's last node now, which is exactly the node in front of the next block.
Code in Python, C++ and Java
Recursion per block
Look k nodes ahead; if the list runs out first, return head unchanged. Otherwise the call on the node after the block returns the already-solved remainder, and the block is reversed with its backward chain starting at that remainder, so the block's first node lands on it. The block's last node is returned as the new head. The depth is the number of blocks, up to 5000 when k = 1, which is over Python's default limit of 1000.
Common pitfalls
Reversing before checking the block is full
# flip nodes while counting to k # stop when the list runs out
# walk k steps to find kth first # flip only if kth exists
On [1, 2, 3, 4, 5] with k = 3, a loop that starts flipping 4 and 5 and then discovers the list has ended returns [3, 2, 1, 5, 4]. The expected answer keeps the short tail: [3, 2, 1, 4, 5].
Moving before to kth instead of the old first node
before.next = kth before = kth
first = before.next before.next = kth before = first
After the flip, kth is the block's front and the old first node is its end. Using kth as the next before makes the second block hang off the wrong node: on [1, 2, 3, 4] with k = 2 the walk for the second block starts from 2, whose next is 1, so it reverses 1 and 3 and returns [2, 3, 1, 4] instead of [2, 1, 4, 3].
Edge cases
Every block has one node; reversing it changes nothing, and the list comes back as it was.
One full block: the whole list is reversed, then the next check finds nothing left and returns.
The last full block's first node ends up pointing at after, which is null, and the following check stops on its first step.
Complexity
kth, once by the reversal. The final short check reads fewer than k more nodes. Only a fixed set of pointers is kept.Reverse Nodes in k-Group FAQ
What changes if the leftover nodes must also be reversed?
Drop the early return. When the walk for kth runs out, reverse whatever is left using null as after, link it, and stop. Some interview variants ask for exactly that.
How is this related to Swap Nodes in Pairs?
Swap Nodes in Pairs is this problem with k = 2. The same code solves it, though pair swapping is usually written with three direct pointer assignments instead of a loop.
Can I copy each block's values into an array and write them back?
It produces the right order but breaks two rules: values are not allowed to change, and an array of size k is not O(1) memory.