TRT
Sign in
mediumFoundationsLeetCode#fixed-gap pointers#dummy head

Remove nth node from end of list

Remove the node n positions from the end of a linked list in one pass, using two pointers a fixed gap apart.

The Runtime Theory Team1 min read
Taught inFast and slow pointersTwo pointers walking a list at different speeds find its middle, the node n from the end, and whether it loops back on itself, all in one pass with O(1) memory.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inhead = [1, 2, 3, 4, 5], n = 2

out[1, 2, 3, 5]

inhead = [1], n = 1

out[]

inhead = [1, 2], n = 2

out[2]

Given the head of a linked list and n, remove the nth node from the end and return the head. Try to do it in one pass.

Before you code

Two passes is easy: count the length, then walk to position length − n. For one pass, keep two pointers exactly n + 1 nodes apart, so that when the front one falls off the end, the back one is just before the node to remove.

Hints

  1. Start both pointers at a dummy node in front of the head.
  2. Move lead n + 1 steps ahead.
  3. Move lead and trail together until lead is null. trail is now the predecessor of the target.
  4. Unlink with trail.next = trail.next.next and return dummy.next, which handles removing the head.

Production & complexity notes

When solving Remove nth node from end of list on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Fast and slow pointers to reinforce the underlying pattern.

What it practices

Pointers kept a fixed distance apart, from Fast and slow pointers.

Not started

Sign in to save your learning progress.

Sign in to save