loading

19. Remove Nth Node From End of List — Step-by-Step Visualization

mediumLeetCode #19Linked ListTwo Pointers

Given the `head` of a linked list, remove the `n`-th node from the end of the list and return its head. **Example 1:** Input: `head = [1,2,3,4,5], n = 2` Output: `[1,2,3,5]` **Example 2:** Input: `head = [1], n = 1` Output: `[]` **Example 3:** Input: `head = [1,2], n = 1` Output: `[1]`

Algorithm Pattern

Two Pointers (Fast & Slow)

Key Idea

Use a dummy node and delay a slow pointer by `n` steps so it lands right before the target node.

Step-by-Step Approach

  1. Initialize a dummy node pointing to the head.
  2. Set two pointers, `left` and `right`, both starting at `dummy`.
  3. Move `right` forward by `n` steps (so there's an `n` gap between `left` and `right`).
  4. Move both `left` and `right` until `right` reaches the end of the list.
  5. Now `left` points strictly to the node before the one we want to remove.
  6. Bypass the target node by setting `left.next = left.next.next`.

Common Gotchas

  • Without a dummy node, removing the head itself requires an edge-case check. The dummy node simplifies this.

Related Problems