LeetCode 19 Remove Nth Node From End - Implementation

The approach

Two pointers with gap of n. Use dummy node to handle edge cases.

function removeNthFromEnd(head, n): dummy = ListNode(0, head) slow = dummy fast = dummy for i in range(n + 1): fast = fast.next while fast: slow = slow.next fast = fast.next slow.next = slow.next.next return dummy.next

O(n)O(n) time, O(1)O(1) space.