Reverse Nodes in k-Group

Hard
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Reverse Nodes in k-Group

Approach

Use a dummy node and process the list in groups of k. For each group: (1) check if k nodes remain by advancing a pointer k times, (2) reverse the k nodes in place, (3) connect the reversed group to the previous group tail. If fewer than k nodes remain, leave them as-is.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Linked List (K-Group Reversal)

Why It Works

Each node is visited at most twice (once to count, once to reverse). The groupPrev pointer tracks where the reversed group should be attached, ensuring groups connect correctly. Leftover nodes stay in original order.

Updated Feb 2026