DSA AnimatorDSA animations
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.

How to solve Remove Nth Node From End of List

LeetCode 19 · Medium · Linked List · Pattern: Two Pointers with Gap

Why the obvious approach is slow

Counting the length, then walking to length minus n, takes two passes. A fixed gap between two pointers does it in one.

The key idea

Add a dummy node before the head, so removing the head is not a special case. Move fast n plus 1 steps ahead of slow. Then move both until fast falls off the end, and slow sits just before the target.

Remember

A gap of n between two pointers finds the n-th from the end. A dummy head removes the edge case of deleting the first node.

Run the animation above on your own input, or watch the 1:15 video explanation of Remove Nth Node From End of List with a dry run and Java code.

More Linked List problems