Medium · Two Pointers
Understand → Visualise → Practice.
Counting from the end of a singly linked list normally needs the length first. A pointer gap does it in one pass.
Send a lead pointer n nodes ahead, then move lead and trail together. When lead reaches the last node, trail sits just before the node to delete.
It handles removing the first node.
Advance lead n + 1 times from the dummy.
trail.next = trail.next.next.
O(L) time with one pass, O(1) space.
Removing the head is the edge case; a dummy node before head avoids special-casing it.
Read the full guide first: Linked Lists.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.