Reverse Nodes in k-Group

Reverse every consecutive group of k nodes in place; leave the trailing remainder untouched.

Hard
Time O(n) Space O(1)
LeetCode
4 min read
linked-list

Problem#

Reverse every k-sized consecutive group of nodes. If the final group has fewer than k nodes, leave it as is.

Examples#

  • [1,2,3,4,5], k = 2[2,1,4,3,5]
  • [1,2,3,4,5], k = 3[3,2,1,4,5]

Constraints#

  • 1 <= k <= n <= 5000.

Hints#

Hint 1
Use a dummy head. For each group, first probe k ahead to confirm the group exists; then reverse it in place; then splice.

Approach#

Dummy node + group pointer. Per group: walk k steps ahead to confirm completeness, reverse those k nodes, splice tail (now-reversed group’s old head) back to the rest.

Solution#

Reverse Nodes in k-Group
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy(0, head);
ListNode* groupPrev = &dummy;
while (true) {
ListNode* kth = groupPrev;
for (int i = 0; i < k && kth; ++i) kth = kth->next;
if (!kth) break;
ListNode* groupNext = kth->next;
// Reverse [groupPrev->next .. kth].
ListNode *prev = groupNext, *curr = groupPrev->next;
while (curr != groupNext) {
ListNode* nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
ListNode* oldHead = groupPrev->next;
groupPrev->next = kth;
groupPrev = oldHead;
}
return dummy.next;
}
};

Editorial#

The dummy node makes splicing the first group uniform. The probe-then-reverse pattern guarantees we only reverse groups of exactly k. The reversal uses groupNext as the stop sentinel (instead of null) so the tail of the reversed group correctly links to the rest of the list.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.