#19

Remove Nth Node From End of List

Medium Gap of n between two pointers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Remove the n-th node from the end of a linked list in one pass and return the head.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: delete the n-th node counted from the end, in one pass.

Why this works: move fast n steps ahead; then move both. When fast hits the end, slow sits right before the target.

Example: 1→2→3→4→5, n = 2

fast ahead by 2when fast is at 5, slow is at 3 → unlink 4 → 1→2→3→5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

No dummy node — removing the first node (n = length) crashes or returns the wrong head.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Linked List
🎬 Episodes 40–45: video coming soon