Remove Nth Node From End of List
LeetCode 19 • Medium • Linked Lists
Remove the n-th node from the end. Dummy + two pointers: move fast n steps, then move both until fast.next is null.
TimeO(L)single pass
SpaceO(1)two pointers
Slow: —
Fast: —
Ready
Press Play. Dummy node + two pointers. Move fast n steps ahead, then move both until fast.next is null. slow.next = slow.next.next.
TimeO(L)single pass
SpaceO(L)call stack
Recursive: recurse(node) returns depth from end. When depth = n+1, we're at the parent — do node.next = node.next.next.
3
Practice until you don't need to look. Use the guide comments below as scaffolding. The green highlights are the nuances to burn into memory.
PATTERN ▸ Fast n steps ahead, then move both O(n) · O(1)
① DUMMY
dummy = ListNode(0)
dummy.next = head
② INIT
slow = fast = dummy
③ ADVANCE FAST N STEPS
for _ in range(n): fast = fast.next
④ MOVE BOTH UNTIL FAST AT END
while fast.next: slow, fast = slow.next, fast.next
⑤ REMOVE & RETURN
slow.next = slow.next.next
return dummy.next
▼ your implementation ▼
Verify your solution: