Remove Nth Node From End of List
Real-world version: Unhook the Nth Wagon from the TailThe statement here is our own: the same inputs, outputs and technique.
A shunting yard models a train as a one-way coupling chain: every wagon carries a load reading and points at the wagon coupled behind it, and the rear wagon points at nothing.
The harness passes plain JSON, so the train arrives as the array wagons, holding the load readings from the front wagon back to the rear one. Your answer takes the same shape: the readings that remain, front wagon first, or an empty array when nothing is left.
Counting from the rear, where the rear wagon is number 1, unhook wagon number n and couple its two neighbours to each other. The crew has one walk down the train from the front, so rebuild the chain, then find and unhook the wagon in a single pass over the couplings while holding only a fixed number of wagon references. Measuring the train's length first and walking it again does not count as a single pass.
Examples
Example 1
- Input
- wagons = [12, 5, 30, 8, 21], n = 2
- Output
- [12, 5, 30, 21]
From the rear, the wagon loaded with 21 is number 1 and the one loaded with 8 is number 2, so 8 rolls away and 30 couples straight to 21.
Example 2
- Input
- wagons = [4, 7], n = 2
- Output
- [7]
Wagon 2 from the rear is the front wagon here, so the train now begins at the wagon loaded with 7.
Example 3
- Input
- wagons = [9], n = 1
- Output
- []
A single wagon is also the rear wagon, and unhooking it leaves an empty train.
Constraints
- 1 <= wagons.length <= 30
- 0 <= wagons[i] <= 100
- 1 <= n <= wagons.length
- Only a fixed number of wagon references may be held, and the couplings may be walked once
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 unhook_from_tail(wagons: list[int], n: int) -> list[int]:public int[] unhookFromTail(int[] wagons, int n)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 9 test cases: 9 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