53. Remove Nth Node from End
Count backward from the tail, with the last node counted as one, and remove the specified node. The removed node may be the original head, so the returned head can change.
Reconnect surviving nodes without copying them. The contract additionally requires detaching the removed node and defines which n values are valid.
Example 1
Input
N0(1)→N1(2)→N2(3)→N3(4)→N4(5), n=2
Output
N0→N1→N2→N4; N3.next=null
Explanation: N3 is second from the end. Splice through its predecessor N2 and detach N3.
Example 2
Input
N0→N1, n=2
Output
N1; N0.next=null
Explanation: The dummy acts as the predecessor of the original head. The caller must use the returned head.
Example 3
Input
N0→N1, n=3
Output
IllegalArgumentException; original N0.next=N1
Explanation: The setup cursor exhausts before establishing its gap, so no splice occurs.
Constraints
0 <= nodes per input list <= 105-231 <= node.value <= 231 - 11 <= n <= node count- The input list is acyclic. n must identify an existing node from the end; see the detailed validation rules in Editorial.
Hints
Hint 1
What would the predecessor index be if the length were known?
Hint 2
A dummy predecessor allows head removal to use the ordinary splice.
Hint 3
Advance fast n edges from dummy, walk both until fast is the tail, then bypass slow.next and detach it.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Remove the second node from the end
[1,2,3,4,5]
2
["N0","N1","N2","N4"]