~/DHRUVUpskilling
← board/DSA/In place reversal LinkedList/dsa-in-place-reversal-linkedlist-02
Backlog·queued

Reverse Nodes in k-Group

DifficultyMedium
PatternIn place reversal LinkedList
TrackDSA
tl;dr

The task is to reverse the nodes in groups of k in a given linked list, where k is a positive integer, and at most the length of the linked list. If any remaining nodes are not part of a group of k, they should remain in their original order.

full write-up

It is not allowed to change the values of the nodes in the linked list. Only the order of the nodes can be modified.

Note: Use only O(1) extra memory space.

Constraints

Let n be the number of nodes in a linked list.

  • 1 ≤ kn ≤ 500
  • 0 ≤ Node.value ≤ 1000

Examples

Example 1

Input: head = [1, 2, 3, 4, 5, 6, 7, 8] k = 3

Explanation:

  • First group of 3: [1, 2, 3] → reversed to [3, 2, 1]
  • Second group of 3: [4, 5, 6] → reversed to [6, 5, 4]
  • Remaining nodes [7, 8] are fewer than k, so they stay in original order.

Output: [3, 2, 1, 6, 5, 4, 7, 8]


Example 2

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

Explanation:

  • First group of 2: [1, 2] → reversed to [2, 1]
  • Second group of 2: [3, 4] → reversed to [4, 3]
  • Remaining node [5] is fewer than k, so it stays as is.

Output: [2, 1, 4, 3, 5]