← DSA Atlas
Dedicated problem page · #25

Reverse Nodes in k-Group

HardLinked Lists and Pointer ManipulationGrouped in-place reversalPointer manipulation with a dummy node
Solve on LeetCode ↗
25
HardLinked Lists and Pointer ManipulationPointer manipulation with a dummy nodeGrouped in-place reversal

Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes k at a time and return the modified list. If the number of remaining nodes is fewer than k, leave them as they are. Node values must not be changed, only the links.

Open official problem prompt ↗
In plain English

Reverse the list in consecutive chunks of size k in place, leaving any final chunk shorter than k unchanged.

Picture it like this

Like flipping fixed-length train cars on a track: you detach a block of k cars, reverse their order, reattach it, and move on, leaving a short final block untouched.

Example
Input
head = [1,2,3,4,5], k = 2
Output
[2,1,4,3,5]
Why
The first two nodes reverse to 2,1; the next two to 4,3; the leftover single node 5 stays in place.
Constraints
The number of nodes is n1 <= k <= n <= 50000 <= Node.val <= 1000
Pattern lesson

See the pattern, then code

Grouped in-place reversal
Recognition clue

Reversing in fixed-size blocks while leaving a short trailing remainder untouched signals a per-group in-place reversal anchored by a group-boundary pointer.

Linked Lists and Pointer Manipulation

Reversal, cycle detection, merging, reordering, or O(1)-space sequence edits.. Process the list one group at a time: locate the kth node to confirm a full group exists, reverse exactly that segment, then stitch the reversed block between the previous group's tail and the next group's head.

New words, made simpleKnow these before the algorithm
group_prev
Pointer to the node just before the group currently being reversed; it holds the incoming connection.
group_next
The node just after the current group; reversal stops when it is reached, and it becomes the new tail's next.
Approaches from first idea to best ideaCompare the trade-offs
ApproachHow it thinksCost
Stack per group

Works but uses O(k) extra memory the pointer method avoids.

Push k nodes onto a stack then pop them to rebuild reversed order.

Time O(n)Space O(k)
Recursion per group

Clean but adds call-stack space and risks recursion depth limits on long lists.

Reverse the first k, recurse on the rest, and link.

Time O(n)Space O(n/k)
The rule we keep true

Invariant

Before each group is processed, group_prev points to the last node of the already-finalized prefix, and everything after group_prev is still in original order.

Why this is correct

Reasoning

Checking for the kth node first guarantees only complete groups are reversed; the standard three-pointer reversal seeded with prev = group_next makes the group's old head point to group_next, so after relinking group_prev.next = kth the chain stays intact and the leftover tail is skipped.

The algorithm in three movesSay these aloud before coding
1Use a dummy node; keep group_prev at the node before the current group

group_prev=dummy, kth=node2

2Walk k steps to find the kth node; if you run off the end, stop and return

reverse [1,2] -> 2 -> 1

3Record group_next as kth.next

reconnect: dummy -> 2 -> 1 -> node3...

4Reverse the group's links so they point backward, stopping at group_next

5Reconnect group_prev to kth and advance group_prev to the old group head

Visual trace

Follow the data, one decision at a time

Input snapshotHighlighted cells are involved in this example
10
21
32
43
54
1 · Readk=2 from dummy
2 · AskFull group?
3 · Update statekth=node2, group_next=node3
4 · ResultGroup [1,2] confirmed.
Key takeaway

The first k=2 nodes are reversed as a block and spliced back between the dummy and the rest.

Code walkthrough

Read the solution in small chunks

Python 3

Do not memorize the whole program. Connect each group of lines to one job in the algorithm.

  1. 1
    Lines 3-4Anchor

    Dummy before head and group_prev give a stable handle for the first group's incoming link.

  2. 2
    Lines 6-10Full-group check

    Walking k steps proves a complete group exists; running off the end returns immediately, leaving the short tail alone.

  3. 3
    Lines 11-16Reverse the segment

    Seeding prev with group_next makes the old head connect to the next group automatically.

  4. 4
    Lines 17-19Reconnect and advance

    group_prev.next = kth attaches the reversed block; the saved old head becomes the next group_prev.

Make it stick

Edge cases, mistakes, and one self-check

E

Edge cases to test

  • k = 1 (list unchanged)
  • k equals list length (whole list reversed once)
  • Length not a multiple of k (trailing remainder untouched)
  • Single node
!

Common beginner mistakes

  • Reversing a partial final group instead of leaving it as-is
  • Seeding the reversal with None instead of group_next, which severs the tail connection
  • Losing the pointer to the old group head needed to advance group_prev
Check your understanding

Why seed the inner reversal's prev with group_next instead of None?