1595. Swap Neighbour Blocks

Medium3.5 points estimatedLinked ListRecursion

A railway yard stores its wagons in a singly linked list and the dispatcher wants to exchange neighbouring wagon groups. Split the list from head into blocks of exactly k nodes, pair them up as block 1 with block 2, block 3 with block 4, and so on, and swap the two blocks of each pair while keeping the order of nodes inside every block. When fewer than 2k nodes remain, those nodes stay exactly as they are. Write swapNeighbourBlocks(head, k) returning the new head, and relink nodes rather than rewriting values. The list has 0 to 10^5 nodes and 1 <= k <= 10^5. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = [1,2,3,4,5,6], k = 2
Output:
[3,4,1,2,5,6]
Explanation:

Blocks (1,2) and (3,4) swap places, and 5, 6 are fewer than 2k = 4 nodes so they stay put.

Example 2

Input:
head = [1,2,3,4,5,6,7,8], k = 4
Output:
[5,6,7,8,1,2,3,4]
Explanation:

Exactly two blocks of four swap places.

Constraints

0 ≤ length ≤ 105

1 ≤ k ≤ 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…