Reverse Nodes in k-Group
Real-world version: Shunting Wagon BlocksThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def shunt_blocks(wagons: list[int], k: int) -> list[int]:public int[] shuntBlocks(int[] wagons, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's