Browse Curriculum
Linked List
Medium
Remove Nth Node From End of List
Remove the nth node from the end of the list.
10 min read
Solve on LeetCodeProblem Understanding
Given the head of a linked list, remove the n-th node from the end of the list and return its head.
Example: 1 -> 2 -> 3 -> 4 -> 5, n = 2. Remove 4. Result: 1 -> 2 -> 3 -> 5.
Attempt 1: Two Pass Algorithm
- Iterate through the list to find the total length
L. - The node to remove is at index
L - n(from start). - Iterate again to the node just before
L - nand change itsnextpointer.
This works but requires traversing the list twice.
Visualizing the Issue
Can we do this in One Pass? Imagine a stick of length n. If we slide this stick along the list so the front end touches the last node, the back end will be exactly at the node we need to remove!
The Intuition: Two Pointers (Gap Method)
- Create a
dummynode pointing to head (to handle removing the first node easily). - Move a
fastpointern + 1steps ahead. - Move both
fastandslow(initially at dummy) untilfastreaches null. slowis now pointing at the node before the target.- Delete target:
slow.next = slow.next.next.
Interactive Walkthrough
Step 1 / 1
Empty List
Initializing...
1x
Watch the gap of size n slide to the end of the list.
ON THIS PAGE
- Problem Understanding
- Attempt 1: Two Pass Algorithm
- Visualizing the Issue
- The Intuition: Two Pointers (Gap Method)
- Interactive Walkthrough
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
