Reverse Nodes in k-Group (LeetCode 25): Solution and Explanation

Hard
Linked List
Recursion

Given a linked list and a number k, reverse the nodes in consecutive blocks of k and return the new head. If the final block has fewer than k nodes, leave it in its original order. Only node links may change, not node values.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

You probably already know how to reverse a whole linked list with three pointers. This problem asks you to apply that same reversal to a series of sections and then stitch the sections back together. A brute force would copy values into an array, reverse each chunk there and write them back, but that breaks the rule about changing links rather than values and costs O(n) extra space.

Think about what you need to know for one group. You need the node right before the group, groupPrev, so you can reconnect it to the new first node. You need the k-th node of the group, kth, which becomes the new first node. And you need the node right after the group, groupNext, so the old first node can point to it once it becomes the group's last node. Finding kth also tells you whether a full group exists; if fewer than k nodes remain, you stop.

The neat part of the reference code is how it reverses. Instead of starting prev at None, it starts prev at kth.next, the node after the group. As each node is flipped, the first node of the group ends up pointing at groupNext automatically, so the reversed group is already linked to the rest of the list.

After reversing, the old first node is now the group's tail, so it becomes the groupPrev for the next round. A dummy node in front of the head means the first group needs no special handling, and dummy.next is the final answer.

Approach: Iterative group reversal with dummy node

  1. Create dummy pointing at head and set groupPrev = dummy.
  2. Find kth by moving k steps from groupPrev with getKth. If it is None, fewer than k nodes remain, so stop.
  3. Record groupNext = kth.next, the first node after the current group.
  4. Reverse the group with prev = kth.next and curr = groupPrev.next, flipping curr.next = prev until curr reaches groupNext.
  5. Save the old first node as tmp = groupPrev.next, set groupPrev.next = kth, and move groupPrev = tmp for the next group.
  6. When the loop breaks, return dummy.next.

Step-by-step example

head = [1,2,3,4,5], k = 2
  1. Start with dummy -> 1 -> 2 -> 3 -> 4 -> 5 and groupPrev = dummy. Two steps forward gives kth = 2, and groupNext = 3.
  2. Reverse with prev = 3: node 1 now points to 3, then node 2 points to 1. curr reaches 3 and stops.
  3. Set dummy.next = 2 and groupPrev = 1. The list is dummy -> 2 -> 1 -> 3 -> 4 -> 5.
  4. From node 1, two steps forward gives kth = 4 and groupNext = 5. Reversing makes 3 point to 5 and 4 point to 3. Set 1.next = 4 and groupPrev = 3.
  5. From node 3, only node 5 remains, so getKth returns None and the loop ends. The result is [2,1,4,3,5].

Code: Python, Java, C++

1class Solution:
2    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
3        dummy = ListNode(0, head)
4        groupPrev = dummy
5        
6        while True:
7            kth = self.getKth(groupPrev, k)
8            if not kth:
9                break
10            groupNext = kth.next
11            
12            # Reverse group
13            prev, curr = kth.next, groupPrev.next
14            while curr != groupNext:
15                tmp = curr.next
16                curr.next = prev
17                prev = curr
18                curr = tmp
19                
20            tmp = groupPrev.next
21            groupPrev.next = kth
22            groupPrev = tmp
23        return dummy.next
24    
25    def getKth(self, curr, k):
26        while curr and k > 0:
27            curr = curr.next
28            k -= 1
29        return curr

Time and space complexity

Time

O(n)

Each node is visited a constant number of times: once while searching for kth and once while being reversed.

Space

O(1)

The reversal is done in place with a fixed number of pointers, and no recursion is used.

Other approaches

Recursive reversal (time O(n), space O(n / k))

Check that k nodes exist, reverse them, and set the old head's next to the result of recursing on the rest of the list. The code is shorter but uses O(n / k) stack frames.

Stack per group (time O(n), space O(k))

Push k nodes onto a stack and pop them to relink in reverse order, leaving a short tail as is. It is easier to get right under pressure but needs O(k) extra memory.

Common mistakes

  • Starting prev at None during the reversal, which disconnects the reversed group from the rest of the list unless you add an extra relinking step.
  • Reading kth.next after the reversal instead of before. Save groupNext first because kth's link changes during the flip.
  • Reversing the final short group. The getKth check must run before any pointers change so a group of fewer than k nodes is left alone.
  • Setting groupPrev = kth after the reversal. The new tail of the group is the old first node, which is why the code saves it in tmp.

Frequently asked questions

Can Reverse Nodes in k-Group be done in O(1) space?

Yes. The iterative approach reverses each group in place with a handful of pointers and uses no recursion, so the extra space is constant.

Why use a dummy node?

The first group's reversal changes the head of the list. A dummy node gives that group a predecessor like every other group, so one piece of code handles all of them.

What happens to the leftover nodes at the end?

If fewer than k nodes remain, they stay in their original order. The code detects this when getKth returns None and stops before touching them.

What is the time complexity?

It is O(n). Each node is passed over a constant number of times, once to confirm the group is full and once to reverse it.