LeetCode #25 Hard

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 k nodes, 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.
Constraints
  • The number of nodes in the list is n.
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000
linked-listrecursion
Open on LeetCode ↗
02

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 at after with no extra step.
  • Then fix the front. before still 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 becomes before for the next block.

A placeholder in front of the head gives the first block a before too.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
▶3 dummy = ListNode(0, head)
▶4 before = dummy
▶5 while True:
▶6 kth = before
▶7 for _ in range(k):
▶8 kth = kth.next
▶9 if not kth:
▶10 return dummy.next
▶11 after = kth.next
▶12 prev, curr = after, before.next
▶13 while curr is not after:
▶14 nxt = curr.next
▶15 curr.next = prev
▶16 prev, curr = curr, nxt
▶17 first = before.next
▶18 before.next = kth
▶19 before = first
start12345nullbeforeplaceholder in front; blocks of 2 nodes
k2
beforestart
The placeholder is the node in front of the first block, so the first block's front seam is rewired the same way as every later one.
start12345nullbeforeafter2 nodes found: 1 to 2 → reverse them
beforestart
kth2
after3
Walking 2 steps from start reached 2, so the block is full. The node after it, 3, is where the reversed block must lead.
start12345nullbeforeafter1 now points to 3, past the block
1 points to3
The backward chain starts at the node after the block, not at nothing. So 1, which will be the block's last node, is already joined to the rest of the list.
start12345nullbeforeafter2 now points back to 1
2 points to1
Same move as reversing a whole list: 2 turns around to the node handled just before it.
start12345nullbeforeafterstart now points to 2; 1 is the new before
start points to2
next before1
start still pointed at 1, the block's old front. It now points at 2. 1 sits at the block's end, right in front of the next block.
start21345nullbeforeafter2 nodes found: 3 to 4 → reverse them
before1
kth4
after5
Walking 2 steps from 1 reached 4, so the block is full. The node after it, 5, is where the reversed block must lead.
start21345nullbeforeafter3 now points to 5, past the block
3 points to5
The backward chain starts at the node after the block, not at nothing. So 3, which will be the block's last node, is already joined to the rest of the list.
start21345nullbeforeafter4 now points back to 3
4 points to3
Same move as reversing a whole list: 4 turns around to the node handled just before it.
start21345nullbeforeafter1 now points to 4; 3 is the new before
1 points to4
next before3
1 still pointed at 3, the block's old front. It now points at 4. 3 sits at the block's end, right in front of the next block.
start21435nullbeforeonly 1 left, fewer than 2 → leave it
nodes left1
The walk to find the block's last node hit the end after 1 step. Nothing has been changed yet, so the short tail keeps its order.
start21435nullreturn 2 → 1 → 4 → 3 → 5
return2
The placeholder's next node is the new head: the last node of the first block.
05

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.

▶1class Solution:
▶2 def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
▶3 node = head
▶4 for _ in range(k):
▶5 if not node:
▶6 return head
▶7 node = node.next
▶8 prev, curr = self.reverseKGroup(node, k), head
▶9 for _ in range(k):
▶10 nxt = curr.next
▶11 curr.next = prev
▶12 prev, curr = curr, nxt
▶13 return prev
06

Common pitfalls

Reversing before checking the block is full

✗ Wrong
# flip nodes while counting to k
# stop when the list runs out
✓ Right
# 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

✗ Wrong
before.next = kth
before = kth
✓ Right
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].

07

Edge cases

k = 1

Every block has one node; reversing it changes nothing, and the list comes back as it was.

k equals the list length

One full block: the whole list is reversed, then the next check finds nothing left and returns.

Length is a multiple of k

The last full block's first node ends up pointing at after, which is null, and the following check stops on its first step.

08

Complexity

Time
O(n)
Space
O(1)
Each node is visited twice: once by the walk that finds kth, once by the reversal. The final short check reads fewer than k more nodes. Only a fixed set of pointers is kept.
09

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.