Show problems as
Classic problem #19MediumLinked ListTwo Pointers

Remove Nth Node From End of List

Real-world version: Unhook the Nth Wagon from the Tail
Tracked in this browser only
Read Remove Nth Node From End of List on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstFast and Slow Pointers · Linked List, animated step by step

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.

Python
def unhook_from_tail(wagons: list[int], n: int) -> list[int]:
Java
public int[] unhookFromTail(int[] wagons, int n)