Coding Interview PatternsRemove Nth Node From End of List
MediumFast and Slow Pointers
Remove Nth Node From End of List
Explanation & Solution
Description
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Input:head = [1,2,3,4,5], n = 2
0
1
1
2
2
3
3
4
4
5
Output:[1,2,3,5]
0
1
1
2
2
3
3
5
Explanation: The 2nd node from the end is 4. After removing it, the list becomes [1,2,3,5].
Constraints
- The number of nodes in the list is
sz 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Approach
Fast and Slow Pointers pattern
1. Create a Dummy Node
- Create a dummy node that points to
head. - This handles the edge case where the head itself needs to be removed (e.g., removing the nth node when
nequals the list length).
2. Advance the Fast Pointer
- Move
fastforward byn + 1steps from the dummy node. - This creates a gap of
nnodes betweenfastandslow.
3. Move Both Pointers Together
- Move both
slowandfastone step at a time untilfastreachesnull. - At this point,
slowis positioned right before the node to be removed.
4. Remove the Target Node
- Set
slow.next = slow.next.nextto skip over the nth node from the end. - This effectively removes it from the linked list.
5. Return the Result
- Traverse the modified list starting from
dummy.nextand collect values into an array. - Return the array.
Key Insight
- The two-pointer technique with an
n-step gap lets us find the nth node from the end in a single pass. - The dummy node eliminates special-case logic for removing the head.
Time
O(L) where L is the length of the list — one pass.Space
O(1)only pointer variables are used (excluding the output array).Visualization
Input:
Linked List Traversal
—
Press play to start traversal
Slow (S)Fast (F)Both
6 steps