Reverse Nodes in k-Group (LeetCode 25): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Create
dummypointing atheadand setgroupPrev = dummy. - Find
kthby moving k steps fromgroupPrevwithgetKth. If it is None, fewer than k nodes remain, so stop. - Record
groupNext = kth.next, the first node after the current group. - Reverse the group with
prev = kth.nextandcurr = groupPrev.next, flippingcurr.next = prevuntilcurrreachesgroupNext. - Save the old first node as
tmp = groupPrev.next, setgroupPrev.next = kth, and movegroupPrev = tmpfor the next group. - When the loop breaks, return
dummy.next.
Step-by-step example
head = [1,2,3,4,5], k = 2
- Start with dummy -> 1 -> 2 -> 3 -> 4 -> 5 and
groupPrev= dummy. Two steps forward giveskth= 2, andgroupNext= 3. - Reverse with
prev= 3: node 1 now points to 3, then node 2 points to 1.currreaches 3 and stops. - Set dummy.next = 2 and
groupPrev= 1. The list is dummy -> 2 -> 1 -> 3 -> 4 -> 5. - From node 1, two steps forward gives
kth= 4 andgroupNext= 5. Reversing makes 3 point to 5 and 4 point to 3. Set 1.next = 4 andgroupPrev= 3. - From node 3, only node 5 remains, so
getKthreturns 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 curr1class Solution {
2 public ListNode reverseKGroup(ListNode head, int k) {
3 ListNode dummy = new ListNode(0, head);
4 ListNode groupPrev = dummy;
5
6 while (true) {
7 ListNode kth = getKth(groupPrev, k);
8 if (kth == null) break;
9 ListNode groupNext = kth.next;
10
11 // Reverse group
12 ListNode prev = kth.next;
13 ListNode curr = groupPrev.next;
14 while (curr != groupNext) {
15 ListNode tmp = curr.next;
16 curr.next = prev;
17 prev = curr;
18 curr = tmp;
19 }
20
21 ListNode tmp = groupPrev.next;
22 groupPrev.next = kth;
23 groupPrev = tmp;
24 }
25 return dummy.next;
26 }
27
28 private ListNode getKth(ListNode curr, int k) {
29 while (curr != null && k > 0) {
30 curr = curr.next;
31 k--;
32 }
33 return curr;
34 }
35}1class Solution {
2public:
3 ListNode* reverseKGroup(ListNode* head, int k) {
4 ListNode* dummy = new ListNode(0, head);
5 ListNode* groupPrev = dummy;
6
7 while (true) {
8 ListNode* kth = getKth(groupPrev, k);
9 if (!kth) break;
10 ListNode* groupNext = kth->next;
11
12 // Reverse group
13 ListNode* prev = kth->next;
14 ListNode* curr = groupPrev->next;
15 while (curr != groupNext) {
16 ListNode* tmp = curr->next;
17 curr->next = prev;
18 prev = curr;
19 curr = tmp;
20 }
21
22 ListNode* tmp = groupPrev->next;
23 groupPrev->next = kth;
24 groupPrev = tmp;
25 }
26 return dummy->next;
27 }
28
29 ListNode* getKth(ListNode* curr, int k) {
30 while (curr && k > 0) {
31 curr = curr->next;
32 k--;
33 }
34 return curr;
35 }
36};Time and space complexity
O(n)
Each node is visited a constant number of times: once while searching for kth and once while being reversed.
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
prevat None during the reversal, which disconnects the reversed group from the rest of the list unless you add an extra relinking step. - Reading
kth.nextafter the reversal instead of before. SavegroupNextfirst becausekth's link changes during the flip. - Reversing the final short group. The
getKthcheck must run before any pointers change so a group of fewer than k nodes is left alone. - Setting
groupPrev = kthafter the reversal. The new tail of the group is the old first node, which is why the code saves it intmp.
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.