Remove Nth Node From End of List - Problem
You're given the head of a singly linked list and need to remove the nth node from the end of the list, then return the modified list's head.
This is a classic linked list manipulation problem that tests your understanding of pointer arithmetic and list traversal techniques. The challenge lies in efficiently locating the nth node from the end without knowing the total length beforehand.
Key Points:
- The list is
1-indexedfrom the end - You must handle edge cases like removing the head node
- The solution should work in a single pass for optimal efficiency
Example: If you have [1,2,3,4,5] and n=2, you should remove the 2nd node from the end (value 4), returning [1,2,3,5].
Input & Output
example_1.py โ Basic Removal
$
Input:
head = [1,2,3,4,5], n = 2
โบ
Output:
[1,2,3,5]
๐ก Note:
Remove the 2nd node from the end (node with value 4). The resulting list becomes [1,2,3,5].
example_2.py โ Single Node
$
Input:
head = [1], n = 1
โบ
Output:
[]
๐ก Note:
Removing the only node from the list results in an empty list.
example_3.py โ Remove Head
$
Input:
head = [1,2], n = 2
โบ
Output:
[2]
๐ก Note:
Remove the 2nd node from the end, which is the head node (1). The list becomes [2].
Visualization
Tap to expand
Understanding the Visualization
1
Create the Window
Position two pointers with exactly the right gap between them
2
Slide the Window
Move both pointers together, maintaining the gap
3
Perfect Positioning
When the front reaches the end, the back is exactly where we need it
4
Execute Removal
Remove the target node with a simple pointer update
Key Takeaway
๐ฏ Key Insight: The two-pointer technique with a fixed gap transforms a two-pass problem into an elegant single-pass solution. This pattern is fundamental to many linked list problems.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the list, visiting each node only once
โ Linear Growth
Space Complexity
O(1)
Only using two pointer variables and one dummy node, constant space
โ Linear Space
Constraints
- The number of nodes in the list is sz
- 1 โค sz โค 30
- 0 โค Node.val โค 100
- 1 โค n โค sz (n is always valid)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code