FunctionRacerProblemsRace

Swap Neighboring Blocks

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

Cut the list into blocks of k nodes from the front. Swap the first block with the second, the third with the fourth, and so on. Inside a block the order stays as it is.

Only two full blocks are swapped: when fewer than 2 * k nodes remain at the end, those nodes stay where they are. Return the head. For 1 -> 2 -> 3 -> 4 -> 5 and k = 2 the result is 3 -> 4 -> 1 -> 2 -> 5. 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 [3,4,1,2,5]

The blocks 1, 2 and 3, 4 trade places. The 5 has no full pair of blocks and stays.

Example 2

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

Two pairs of blocks: 3, 4 moves in front of 1, 2, and 7, 8 in front of 5, 6.

Example 3

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

Three nodes are fewer than two blocks of two.

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