Remove the nth node from the end of a linked list and return its head.
Move fast n + 1 steps ahead of slow (both starting at a dummy). Then move both until fast falls off the end; slow is right before the target.
1function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {2const dummy = new ListNode(0, head);3let slow: ListNode = dummy, fast: ListNode | null = dummy;4for (let i = 0; i <= n; i++) fast = fast!.next;5while (fast) { slow = slow.next!; fast = fast.next; }6slow.next = slow.next!.next;7return dummy.next;8}
Both pointers start at the dummy.
Space: play/pause · ←/→: step