PracticeNeetCode ↗LeetCode ↗
Given the head of a linked list, remove the nth node from the end of the list and return the head.
n find "n from the end" in a single pass — no need to know the list's length first.head removes the special case where the node to delete is the head itself.n + 1 steps first, then move both together; when fast reaches the end, slow sits right before the target node.head; set slow = dummy, fast = dummy.fast n + 1 steps ahead of slow.slow and fast together, one step at a time, until fast is None.slow.next = slow.next.next, then return dummy.next.Time: O(n) — Space: O(1)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
dummy = ListNode(0, head)
slow = fast = dummy
for _ in range(n + 1):
fast = fast.next
while fast:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.nextHow the solution above works, piece by piece.
dummy = ListNode(0, head) sits before the head, so removing the first node works the same as any other.fast n + 1 steps: now there are exactly n nodes between slow and fast.fast is None. The gap is preserved, so slow stops just before the n-th node from the end.slow.next = slow.next.next unlinks it.dummy.next (the head may have changed). One pass: O(length) time, O(1) space.Running it on head = [1, 2, 3, 4, 5], n = 2:
fast exactly n + 1 nodes ahead means that when fast falls off the end, slow is right before the node to delete. The dummy node (d) handles deleting the real head with no special case.