Remove Nth Node From End of List
Medium Two Pointers
head is the head of a singly linked list of at least one node, and n is a whole number from 1 to the number of nodes.
Count the nodes from the tail: the tail is node 1 from the end, the node before it node 2 from the end, and so on. Remove node n from the end, so that the node before it links to the node after it.
Return the head of the list that is left, or null if no node is left.
Example 1
Input: head = [7,3,9,4,2], n = 3
Output: [7,3,4,2]
Counting from the tail, 2 is node 1 from the end, 4 node 2 and 9 node 3 from the end. With 9 gone, 3 links to 4.
Example 2
Input: head = [5,8], n = 2
Output: [8]
Example 3
Input: head = [4,4,1,4], n = 1
Output: [4,4,1]
Constraints
1 ≤ number of nodes ≤ 2 × 10⁵-10⁹ ≤ node.val ≤ 10⁹1 ≤ n ≤ number of nodes
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
See the AI roundWatch the explanation
More Two Pointers
- Trapping Rain WaterAI round · Hard
- 3SumAI round · Medium
- Container With Most WaterAI round · Medium
- Longest Palindromic SubstringAI round · Medium
- Find the Duplicate NumberAI round · Medium