Remove Nth Node From End of List - Problem
Given the head of a linked list, remove the n-th node from the end of the list and return its head.
The list is 1-indexed from the end, meaning the last node is the 1st node from the end, the second-to-last is the 2nd node from the end, and so on.
Follow up: Could you do this in one pass?
Input & Output
Example 1 — Remove Middle Node
$
Input:
head = [1,2,3,4,5], n = 2
›
Output:
[1,2,4,5]
💡 Note:
Remove the 2nd node from the end, which is node 4. The 2nd from end (n=2) is at position 4 (1-indexed), so we remove it and return [1,2,4,5].
Example 2 — Remove Head
$
Input:
head = [1], n = 1
›
Output:
[]
💡 Note:
There's only one node and we need to remove the 1st (and only) node from the end. Result is an empty list.
Example 3 — Remove Last Node
$
Input:
head = [1,2], n = 1
›
Output:
[1]
💡 Note:
Remove the 1st node from end (which is the last node). Remove node 2 and return [1].
Constraints
- The number of nodes in the list is sz
- 1 ≤ sz ≤ 30
- 0 ≤ Node.val ≤ 100
- 1 ≤ n ≤ sz
Visualization
Tap to expand
Understanding the Visualization
1
Input
Linked list [1,2,3,4,5] and n=2
2
Process
Find and remove 2nd node from end (node 4)
3
Output
Modified list [1,2,4,5]
Key Takeaway
🎯 Key Insight: Two pointers with n-gap eliminates need to count total nodes, solving in one pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code