The node is identified relative to the list end, but only one forward pass is allowed, so a leading pointer can convert distance-from-end into a simultaneous stopping position.
Keep true
After the initial advance, right remains exactly n links ahead of left. Therefore, when right is the tail, left.next is the nth node from the end.
Reuse it
Use a fixed lead whenever a linked-list target is defined by distance from the end; add a dummy when the operation may change the head.
Read it this way: A dummy points to 1, so removing the head would use the same link update. Both left and right start at dummy. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: Two pointers with a fixed gap.
Simple idea: Move right ahead by n nodes. Then move both pointers together. When
right reaches the end, left is just before the node to remove. A dummy node handles
removing the head without a special case.
def remove_nth_from_end(head: ListNode | None, n: int) -> ListNode | None: dummy = ListNode(0, head) left = dummy right = dummy for _ in range(n): if right.next is None: return head right = right.next while right.next: left = left.next right = right.next if left.next: left.next = left.next.next return dummy.next
Cost:O(n) time and O(1) space.
The platform supplies ListNode with val and next; this snippet assumes that definition.