Remove the nth node from the end in one pass: start a fast runner n steps ahead, move both until it falls off, then unlink the next node.
▼The problem
LeetCode 19 (Medium). Given the head of a linked list, remove the nth node from the end of the list and return its head.
Examples (LeetCode's, all three animated): head = [1,2,3,4,5], n = 2 → [1,2,3,5] (the example, the key idea and the walkthrough), [1], n = 1 → [] (why the dummy) and [1,2], n = 1 → [1] (acted out beside the code).
The solution
def removeNthFromEnd(head, n):
dummy = ListNode(0, head)
fast = slow = dummy
for _ in range(n + 1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.nextTranscript
Remove Nth Node From End of List. You get the head of a linked list and a number n. Remove the nth node from the end, and return the head.
Take one through five, with n equal to two. Count back from the end: five is first, four is second. So four goes, and we get one, two, three, five.
However, a linked list only points forward, so you can't walk back from the tail. The simple way walks twice. First, count the length: five. Then walk again to node five minus two, three, right before the target, and skip four. It works, but it reads the list twice. Can we do it in one pass?
Rope two climbers together, slow and fast, on a dummy node in front of the head. Fast climbs n plus one steps ahead: three, for n of two. Then both step together, keeping that gap, until fast falls off the end. Now slow stands exactly one node before the target.
Let's watch it. Fast climbs: one, two, three. Now together: slow one, fast four. Slow two, fast five. Slow three, and fast falls off. Slow's next is four, so point it past four, at five. Four is gone: one, two, three, five.
Why the dummy? Take a single node with n of one. Fast climbs two and falls straight off, so slow never leaves the dummy. Skipping the dummy's next removes the head itself, and the list is empty. Without a dummy, there's no node before the head.
In code, make the dummy and start both pointers on it. Move fast n plus one times. While fast isn't null, step both. Then set slow dot next to slow dot next dot next, and return dummy dot next.
One pass: order L time, for a list of length L. And the space is constant: a dummy and two pointers.
Rope up, walk to the edge, snip. That's Remove Nth Node From End of List.