Reverse Nodes in k-Group
Pattern: Reversal
Work group by group. Check that k nodes are left; reverse them so the group's first node ends up pointing at the next group; link the previous part to the group's old last node; move on. A short final group stays as it is.
The problem
Given the head of a linked list and k, reverse the nodes in each consecutive group of k, and return the new head. If
fewer than k nodes remain at the end, leave them in order. Change links, not values. For example,
1 → 2 → 3 → 4 → 5 with k = 2 becomes 2 → 1 → 4 → 3 → 5, and with k = 3 becomes 3 → 2 → 1 → 4 → 5.
The function name reverseKGroup matches LeetCode. Use the link above for the exact statement and limits.
Think first
- How do you know a full group is left?
- After reversing a group, which node must the previous group point to? Which node points to the next group?
- What do you need to remember between groups?
Hints
Brute force, and why it fails
Copy values into an array, reverse each block, write them back: O(n) memory, and it changes values. Reversing links in place uses O(1) memory.
The key insight
Starting prev at the node after the group makes the reversed group already joined to what follows. Only one more link,
from the node before the group, needs fixing.
Dry run
The list is 1 → 2 → 3 → 4 → 5 and k = 2. groupPrev starts on a dummy. The first group is 1 2, and kth is the 2.
The plan
dummy.next = head, groupPrev = dummy
loop:
kth = k steps after groupPrev; if missing: stop
groupNext = kth.next
prev = groupNext, cur = groupPrev.next
while cur != groupNext: next = cur.next; cur.next = prev; prev = cur; cur = next
first = groupPrev.next
groupPrev.next = kth
groupPrev = first
return dummy.next
Complexity
- Time
O(n)- Space
O(1)
Each node is checked once while counting and once while reversing.
Edge cases
k = 1: unchanged.kequal to the length: the whole list is reversed.klarger than the length: unchanged.
I've built my logic, show the code
Java
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode groupPrev = dummy; // the node just before the current group
while (true) {
ListNode kth = groupPrev;
for (int i = 0; i < k && kth != null; i++) kth = kth.next;
if (kth == null) break; // fewer than k nodes left: leave them
ListNode groupNext = kth.next;
ListNode prev = groupNext, cur = groupPrev.next; // reverse the group, pointing its first node at groupNext
while (cur != groupNext) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
ListNode first = groupPrev.next; // was first, is now last in the group
groupPrev.next = kth; // the group's old last node now comes first
groupPrev = first;
}
return dummy.next;
}
}C++
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy(0);
dummy.next = head;
ListNode* groupPrev = &dummy; // the node just before the current group
while (true) {
ListNode* kth = groupPrev;
for (int i = 0; i < k && kth != NULL; i++) kth = kth->next;
if (kth == NULL) break; // fewer than k nodes left: leave them
ListNode* groupNext = kth->next;
ListNode *prev = groupNext, *cur = groupPrev->next; // reverse the group onto groupNext
while (cur != groupNext) {
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
ListNode* first = groupPrev->next; // was first, is now last in the group
groupPrev->next = kth; // the group's old last node now comes first
groupPrev = first;
}
return dummy.next;
}
};Python
from lib import ListNode
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
dummy = ListNode(0, head)
group_prev = dummy # the node just before the current group
while True:
kth = group_prev
for _ in range(k):
kth = kth.next
if kth is None:
return dummy.next # fewer than k nodes left: leave them
group_next = kth.next
prev, cur = group_next, group_prev.next # reverse the group, pointing its first node at group_next
while cur is not group_next:
cur.next, prev, cur = prev, cur, cur.next
first = group_prev.next # was first, is now last in the group
group_prev.next = kth # the group's old last node now comes first
group_prev = firstCommon mistakes
- Reversing the final short group.
- Starting
prevat null, which cuts the group off from the rest. - Moving
groupPrevtokthinstead of the group's old first node.