Introduction
The Remove Nth Node From End problem involves deleting the nth node from the end of a linked list.
The task is to:
- find nth node from end
- remove it safely
- maintain linked list structure
Example:
Input:1 -> 2 -> 3 -> 4 -> 5
n = 2
Output:
1 -> 2 -> 3 -> 5
Explanation:
2nd node from end is: 4Remove node 4.
Updated list:
1 -> 2 -> 3 -> 5
This problem is one of the most important applications of:
Two Pointer TechniqueConstraints
1 <= Number of Nodes <= 10^51 <= n <= Number of NodesApproach 1 : Brute Force (Using Length Calculation)
Explanations:
Explanation:
The idea is:
- calculate linked list length
- find node before target
- remove nth node
Steps:
- Find total length.
- Locate node before target.
- Delete target node.
This approach works but:
- requires two traversals
So two pointer solution is preferred.
Dry Run
Input:
1 -> 2 -> 3 -> 4 -> 5
n = 2
Length:
5
Target position:
5 - 2 = 3
Remove:
4
Output:1 -> 2 -> 3 -> 5
Practice :
Complexity Analysis :
Time Complexity:- O(n)
Explanation :
Linked list is traversed twice.
Space Complexity:- O(1)
Explanation :No extra space is used.
Approach 2 : Optimal Solution(Using Two Pointers)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- move fast pointer n steps
- move slow and fast together
- slow reaches node before target
This removes node in:
- single traversal
Dry Run
Input:1 -> 2 -> 3 -> 4 -> 5
n = 2
Fast moves:
2 steps ahead
Move both pointers.
Slow reaches:
3
Delete:
4
Output:
1 -> 2 -> 3 -> 5
Practice :