Reverse Nodes in K-Group
01 · Problem
Given the head of a singly linked list and a positive integer k, split the list into consecutive groups of k nodes starting from the head and reverse the order of nodes inside each full group. If the number of remaining nodes at the end is less than k, leave that last partial group in its original order.
Return the head of the modified list. Only the links between nodes may change; node values must not be modified.
02 · Examples
head = [1,2,3,4,5,6,7], k = 3
[3,2,1,6,5,4,7]
Groups are [1,2,3], [4,5,6] and a partial [7]. The two full groups are reversed; [7] stays as is.
head = [1,2,3,4,5], k = 2
[2,1,4,3,5]
Groups [1,2] and [3,4] are reversed; the leftover [5] is shorter than k and is unchanged.
head = [1,2,3,4,5,6], k = 6
[6,5,4,3,2,1]
The whole list forms one full group of size 6, so it is fully reversed.
03 · Constraints
- 01The number of nodes in the list is n, where 1 <= n <= 5000.
- 021 <= k <= n
- 030 <= Node.val <= 1000
04 · Optimal complexity
- Time
- O(n)
- Space
- O(1)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.