LeetCode 19 Remove Nth Node From End - Example and Complexity Analysis

Walkthrough and analysis

Trace 1 → 2 → 3 → 4 → 5 with n = 2.

Create dummy: dummy → 1 → 2 → 3 → 4 → 5.

Initialize: slow = dummy, fast = dummy.

Advance fast by n + 1 = 3 steps: fast = 2.

Move both until fast is null:

  • slow = 1, fast = 3
  • slow = 2, fast = 4
  • slow = 3, fast = 5
  • slow = 3, fast = null (stop)

slow is at node 3. Remove next: slow.next = slow.next.next.

Result: 1 → 2 → 3 → 5.

One pass through the list. O(n)O(n) time. Only two pointers. O(1)O(1) space.