← Back to DSA Animator
Remove Nth Node From End of List LC #19 Medium Two Pointers · Gap Technique
Problem

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Explanation: Remove 4, the 2nd node from the end.
Example 2
Input: head = [1], n = 1
Output: []
Explanation: Remove the only node (the head).
Example 3
Input: head = [1,2], n = 1
Output: [1]
Explanation: Remove 2, the 1st node from the end (tail).
Constraints: 1 ≤ sz ≤ 30  |  0 ≤ Node.val ≤ 100  |  1 ≤ n ≤ sz
Try Examples
Custom:
Linked List
gap = n+1
State Variables
fast idx
0
slow idx
0
gap (target: n+1)
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Create dummy node before head; set both fast and slow to dummy
2
Advance fast exactly n+1 steps to establish a gap of n+1
3
Move both fast and slow together until fast == null
4
slow.next is the target node; bypass it: slow.next = slow.next.next
5
Return dummy.next (handles head-removal edge case)
Time
O(n)
Space
O(1)
Why the Gap Works

When fast is n+1 ahead of slow and they move in lockstep, the moment fast falls off the end (null), slow sits exactly at the node before the one we want to delete. The dummy node means we never have to special-case removing the head — slow's .next is always the real target.