Reverse Nodes in K-Group
You are given a singly linked list represented as an array of node values and an integer k. Reverse every complete group of k consecutive nodes in place. If…
You are given a singly linked list represented as an array of node values and an integer `k`. Reverse every **complete** group of `k` consecutive nodes in place. If the final group has **fewer than k nodes**, leave it in its original order — do not reverse it. Return the head of the modified list. Indices are **0-based**: node 0 is the head, node 1 is the second node, and so on. For example, with `arr = [1, 2, 3, 4, 5]` and `k = 2`, the groups are [1, 2] (complete, reversed → [2, 1]), [3, 4] (complete, reversed → [4, 3]), and [5] (incomplete, left unchanged). The result is `[2, 1, 4, 3, 5]`. Solve it in O(n) time and O(1) extra space by rewiring the existing next pointers — do not copy node values.
- `1 <= nodes.length <= 5000` - `-5000 <= nodes[i] <= 5000` - `1 <= k <= nodes.length` - An incomplete final group (fewer than k nodes) must be left in its original order. - Indices are 0-based: the head is position 0. - Solve in O(n) time and O(1) extra space by rewiring next pointers.
Example 1: input arr = [1,2,3,4,5], k = 2; output [2, 1, 4, 3, 5]. Groups of 2: [1,2] reversed → [2,1]; [3,4] reversed → [4,3]; [5] has only 1 node (fewer than k=2), left unchanged.
Example 2: input arr = [1,2,3,4,5], k = 3; output [3, 2, 1, 4, 5]. Groups of 3: [1,2,3] reversed → [3,2,1]; [4,5] has only 2 nodes (fewer than k=3), left unchanged.
Example 3: input arr = [1,2,3], k = 3; output [3, 2, 1]. Exactly one complete group of k=3: [1,2,3] reversed → [3,2,1]. No tail remainder.
Category: Linked List. Topic: linked-list. Difficulty: Medium. Patterns: linked-list-traversal, in-place-reversal.