FunctionRacerProblemsRace

Reverse Groups From the End

HardLinked listsPython, JavaScript, TypeScript, Java, C++

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

head [1,2,3,4,5]
k 2
returns [1,3,2,5,4]

The node 1 stays in front. The groups 2, 3 and 4, 5 are each turned around.

Example 2

head [1,2,3,4,5,6]
k 3
returns [3,2,1,6,5,4]

Six nodes make two full groups of three, with nothing left over.

Example 3

head [1,2,3]
k 5
returns [1,2,3]

Three nodes cannot fill a group of five, so nothing changes.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems