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
- Start both pointers at a dummy node in front of the head.
- Move
leadn + 1 steps ahead. - Move
leadandtrailtogether untilleadis null.trailis now the predecessor of the target. - Unlink with
trail.next = trail.next.nextand returndummy.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.