Remove Nth Node From End of List
mediumTests passed 2026-11-11v1.0.01. Core Invariant / The Trick
Attach a `dummy` before `head`. Advance `right` `n + 1` steps ahead of `left = dummy`, or advance `right` `n` steps then step both until `right.next == null` so `left` lands cleanly on the predecessor.
2. Complexity Bounds & Proof
Single one-pass scan preserving exact `n`-node separation between `left` and `right`.
3. Minimal Idiomatic Code
def removeNthFromEnd(head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
left = right = dummy
for _ in range(n):
right = right.next
while right.next:
left = left.next
right = right.next
left.next = left.next.next
return dummy.next4. Failure Modes & Interview Follow-ups
Pitfalls:- Deleting the head node (`n == length`) crashes without a dummy node before `head`.
- Off-by-one step count stops `left` on the target node instead of its predecessor.
Follow-ups:- Delete the Middle Node of a Linked List uses `dummy` + fast/slow pointers with the same predecessor pattern.
Personal Notes & Scratchpad (Local-First Yjs CRDT)
Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.
Related Invariants
Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.