All problems
0097HardLinked ListRecursion

Shunting Wagon Blocks

Tracked in this browser only
Write code

Trains the technique from

LeetCode 25Reverse Nodes in k-Group

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A rail yard holds one chain of coupled wagons. The chain is handed to you as wagons, the list of wagon numbers read from the locomotive end to the far end, so wagons[0] is coupled closest to the locomotive and each wagon is coupled only to its neighbours.

The shunter works from the locomotive end and takes the chain in consecutive blocks of k wagons. Every block that is complete gets turned around, so its wagons come back coupled in the opposite order while the block stays where it was in the chain. If fewer than k wagons remain at the far end, that leftover stretch is left exactly as it is.

Re-couple the wagons where they stand: rearrange wagons in place, using only a constant amount of extra space beyond the input, then return it. Wagon numbers may repeat, since two wagons can carry the same load code.

Examples

Example 1

Input
wagons = [7, 2, 9, 4, 5, 6], k = 3
Output
[9, 2, 7, 6, 5, 4]

The first block holds 7, 2, 9 and comes back as 9, 2, 7. The second holds 4, 5, 6 and comes back as 6, 5, 4.

Example 2

Input
wagons = [3, 1, 4, 1, 5, 9, 2], k = 5
Output
[5, 1, 4, 1, 3, 9, 2]

Only one complete block of five exists, so it is turned around. The remaining stretch 9, 2 is too short to shunt and keeps its coupling.

Example 3

Input
wagons = [4, 4, 9], k = 1
Output
[4, 4, 9]

Blocks of one wagon come back the way they went in, so the chain is unchanged.

Constraints

  • n is the number of wagons in the chain
  • 1 <= k <= n <= 5000
  • 0 <= wagons[i] <= 1000
  • The rearrangement must happen in place, using O(1) extra space beyond the input

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def shunt_blocks(wagons: list[int], k: int) -> list[int]:
Java
public int[] shuntBlocks(int[] wagons, int k)
September 7
Apply