Reverse Nodes in k-Group LeetCode Hard #25

Strict In-Place Pointer Reversal Visualizer · O(N) Time, O(1) Extra Space

k = 2
Step: 0 / 0
Active Pointer Indicators:
dummy
Anchor sentinel node pointing to real head. Simplifies edge reversals at head.
groupPrev
The node strictly before the current k-group chunk. Its .next will be linked to the new chunk head (kth).
kth
The k-th node from groupPrev. Becomes the new head of this reversed subsegment.
curr & prev
Iterative link flippers: curr.next = prev inside the group.
groupNext
The first node of the upcoming chunk (kth.next), used as initial prev value to maintain onward connection.
Linked List State Initial List
Ready to execute.
Current k-Group Window
Leftover Untouched (< k)
← / → Active Pointer Inversion
Anchor: dummy.next = head
1

Step 1: Look Ahead (Check k nodes)

Pass 1 / Iteration 1

We initialize a sentinel dummy node pointing to the head. We then advance kth by k steps from groupPrev to see if a complete group exists.

1. Look Ahead

Verify at least k nodes remain. If not, finish early.

2. Link Flip

Standard in-place reversal of arrows using curr and prev.

3. Stitching

Connect previous tail to new head, and advance groupPrev.

groupPrev: dummy
kth: Node 2
curr: None
prev: None
groupNext: Node 3
O(N)
Time Complexity O(N) Linear

Every node is visited at most 2 times: once by the kth lookahead counter to validate group size, and once by the pointer reversal step (curr.next = prev). Total operations = 2N ∈ O(N).

O(1)
Auxiliary Space O(1) Strict Constant

Strictly in-place pointer manipulation. Only 5 pointer variables (dummy, groupPrev, kth, curr, prev, temp) are maintained without recursion stacks or external list nodes.

solution.py (Synchronized)
Live Trace
01def reverseKGroup(head, k):
02 dummy = ListNode(0, head)
03 groupPrev = dummy
04 while True:
05 kth = groupPrev
06 for _ in range(k):
07 kth = kth.next
08 if not kth:
09 return dummy.next
10 prev = kth.next
11 curr = groupPrev.next
12 while curr != kth.next:
13 temp = curr.next
14 curr.next = prev
15 prev = curr
16 curr = temp
17 nextGroupPrev = groupPrev.next
18 groupPrev.next = kth
19 groupPrev = nextGroupPrev
Active Variable: dummy initialized In-place algorithm

Problem Constraints & Edge Cases Handled

1. Leftover Tail Retention If the number of nodes is not a multiple of k, the remaining nodes must keep their original order.
2. Strictly Pointer Reversal Values in the list's nodes cannot be altered. Only memory pointers (node.next) are redirected.
3. Constant Extra Memory Must run in O(1) memory. Array copying or converting to Python list is forbidden.