Reverse Groups From the End
Cut the list into groups of k nodes, counted from the end: the last k nodes are one group, the k nodes before them the next, and so on. If the number of nodes is not a multiple of k, the nodes left over at the front form no group.
Reverse every group and leave the leftover nodes as they are. Return the head. For 1 -> 2 -> 3 -> 4 -> 5 and k = 2 the groups are [2,3] and [4,5], and 1 is left over. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
The node 1 stays in front. The groups 2, 3 and 4, 5 are each turned around.
Example 2
Six nodes make two full groups of three, with nothing left over.
Example 3
Three nodes cannot fill a group of five, so nothing changes.
Constraints
0 <= number of nodes <= 60-100 <= node.val <= 1001 <= k <= 60
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Reverse Nodes in K-GroupHard
- Smallest TurnHard
- Subtract Two NumbersHard
- Swap Neighboring BlocksHard
- Alternating SumBeginner
- Are the Lists EqualBeginner
- Average of the ValuesBeginner
- Balanced Open and CloseBeginner