CodingNodes / Linked List / Remove Nth Node From End of List System design Space play · ←→ step · R restart

Problem

You get the head of a singly linked list and a number n. Delete the node that is n places from the end of the list, where n = 1 means the last node.

Return the head of the list after the removal. The list can become empty.

Constraints

  • 1 ≤ number of nodes ≤ 30
  • 0 ≤ Node.val ≤ 100
  • 1 ≤ n ≤ number of nodes

Examples: pick one to animate

Solutions

TimeO(L) SpaceO(1)

Time: fast walks the list once. slow follows behind and never goes further than fast.

Space: Only the dummy node and two pointers are used.

Put a dummy before the head. Send fast n steps ahead, then move fast and slow together. When fast stands on the last node, slow stands on the node just before the one to remove, because the gap between them is n. The dummy covers the case where the head itself must go.