Visualize

Pattern visualizer

Remove Nth Node From End of List

A singly linked list has no length counter and no way to look backward, so 'the node n from the end' can't be indexed directly without first walking the whole list to measure it. The trick: keep a fixed gap of n+1 nodes between two pointers — advance fast that far ahead, then walk both forward together, and by the time fast falls off the end, slow is automatically sitting one node before the target, the gap having done the counting for you. Reach for it when removing a node by its position from the list's end. Animated on: Remove the 2nd node from the end of [1,2,3,4,5] → result [1,2,3,5].

Linked List

step 1 / 7
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
line 2

Input [1,2,3,4,5], n=2 (remove 2nd from end). dummy sits before idx0. slow=fast=dummy.

Pseudocode
1FUNCTION removeNthFromEnd(head, n):
2 make a dummy node placed before head
3 slow = dummy; fast = dummy
4 move fast forward n+1 times (from i=0 through n)
5 WHILE fast is not empty: move slow one forward; move fast one forward
6 make slow skip over the node after it (slow.next = slow.next.next)
7 RETURN the node after dummy
8END FUNCTION

← / → step · space play · Home restart

Where to practice Linked List