Coding Interview PatternsReverse Nodes in k-Group
HardIn-Place Manipulation of a Linked List

Reverse Nodes in k-Group

Explanation & Solution

Description

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then the remaining nodes at the end should remain as-is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

Input:head = [1,2,3,4,5], k = 2
0
1
1
2
2
3
3
4
4
5
Output:[2,1,4,3,5]
0
2
1
1
2
4
3
3
4
5

Explanation: Reverse in groups of 2: [1,2] becomes [2,1], [3,4] becomes [4,3], and [5] stays.

Constraints

  • The number of nodes in the list is n
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

Approach

In-Place Manipulation of a Linked List pattern

1. Create a Dummy Node

  • Create a dummy node before head to simplify pointer updates.
  • groupPrev tracks the node right before the current group to reverse.

2. Find the k-th Node

  • From groupPrev, advance k steps to find kth.
  • If we can't advance k times (fewer remaining nodes), we're done — leave the remaining nodes as-is.

3. Reverse the Current Group

  • Save groupNext = kth.next (the node after the group).
  • Set prev = groupNext so the reversed group's tail connects to the rest of the list.
  • Reverse k nodes by iterating and flipping pointers.

4. Reconnect and Advance

  • After reversal, prev points to the new front of the group (was kth).
  • groupPrev.next = prev connects the previous part to the reversed group.
  • Move groupPrev to tail (the original first node, now the last in the reversed group).
  • Repeat for the next group.

🧠 Key Insight

  • The key is checking whether k nodes remain before attempting reversal.
  • Each group reversal is just the standard linked list reversal applied to a sublist.
Time
O(n)each node is visited at most twice (once to count, once to reverse).
Space
O(1)only pointer variables are used.

Visualization

Input:
Linked List Traversal
1021324354null

Press play to start traversal

Slow (S)Fast (F)Both
4 steps

Solution Code