DSA Tracker

Visualize

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.

Details

Animated on: Remove the 2nd node from the end of [1,2,3,4,5] → result [1,2,3,5]

Problem:Remove Nth Node From End of ListMedium

Pattern:Fast and Slow Pointers

Linked List

step 1 / 7

1
[0]
2
[1]
3
[2]
4
[3]
5
[4]

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

Every step in words

Show all 7 steps
  1. Input [1,2,3,4,5], n=2 (remove 2nd from end). dummy sits before idx0. slow=fast=dummy.
  2. Advance fast n+1=3 steps ahead: dummy→idx0(1)→idx1(2)→idx2(3). fast lands on idx2, slow stays at dummy — a 3-node gap now separates them.
  3. 1st together-step: slow=slow.next → idx0(1). fast=fast.next → idx3(4). Gap of 3 preserved.
  4. 2nd together-step: slow → idx1(2). fast → idx4(5), the last real node.
  5. 3rd together-step: slow → idx2(3). fast advances past idx4 to null — the while condition (fast !== null) now fails, loop exits.
  6. slow (idx2, value 3) sits right before the target. slow.next = slow.next.next bypasses idx3 (value 4), splicing it out of the list.
  7. Final list [1,2,3,5] — node 4 (2nd from the end) removed, dummy.next returned as the new head.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.