SDE & MLE Prep

19. Remove Nth Node From End of List

Problem

Remove the n-th node from the end of a linked list and return the head.

Example: 1→2→3→4→5, n = 2 → 1→2→3→5

Constraints: follow-up: one pass.

Advance fast n steps ahead from a dummy, then move both until fast is last; slow.next is the node to delete.

dummy 1 2 3 4 5, n=2
fast moves 2 ahead; then both move until fast at 5:
slow at 3 -> skip 4 -> 1 2 3 5

Complexity: O(n) time, one pass.

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        slow = fast = dummy
        for _ in range(n):
            fast = fast.next
        while fast.next:
            slow, fast = slow.next, fast.next
        slow.next = slow.next.next
        return dummy.next