Optimal: gap pointers from a dummy
Time O(L) Space O(1)Both start at the dummy. Move fast n + 1 steps. Then move both until fast is null; slow is just before the node to delete. Skip it.
head = [1, 2, 3, 4, 5], n = 2Step 1/4Both start at the dummy d. Move fast 3 steps (n + 1).
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head), slow = dummy, fast = dummy;
for (int i = 0; i <= n; i++) fast = fast.next; // n + 1 steps ahead
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}Verdict: One pass, and the dummy handles n = length.