25/670

25. Reverse Nodes in k-Group

Hard

Cut a linked list into consecutive blocks of k nodes and reverse each complete block in place, keeping the blocks themselves in their original order. If fewer than k nodes remain at the end, that leftover tail is left exactly as it was.

Your function receives the node values as an integer array (in list order) together with the integer k, and returns the values after every full k-block has been reversed. With k = 1 nothing changes; with k equal to the length, the whole list flips.

This is the general form of Swap Nodes in Pairs (k = 2) — the challenge in the pointer version is stitching each reversed block back to its neighbors without losing the chain.

k = 3: full blocks flip in place, the short tail survives
beforeblock of k = 3 → reverse12345fewer than k left: keepafter32145

Example 1:

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

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

Explanation: Blocks of two: [1,2] flips to [2,1] and [3,4] flips to [4,3]; the lone 5 is an incomplete block and stays.

Example 2:

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

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

Explanation: The first three nodes reverse to [3,2,1]; only two nodes remain, fewer than k, so [4,5] is untouched.

Constraints:

  • 1 ≤ list length ≤ 500
  • 1 ≤ k ≤ list length
  • -1000 ≤ node value ≤ 1000

Hints:

Solve one block first: how do you reverse exactly k nodes, and what should the block's new tail (the old first node) point to afterwards?

Before reversing, look ahead: only flip a block if k nodes actually remain — otherwise stop and keep the tail as-is.

Recursively: reverse the first k nodes, then the answer for the rest is the same problem; attach it after the flipped block. Iteratively, a two-pointer swap inside each window gives O(1) extra space.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: [2, 1, 4, 3, 5]