AceYourInterviews
Checking sign-in…

53. Remove Nth Node from End

CoreDummy predecessor and fixed pointer gap

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 - 1
  • 1 <= 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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Remove the second node from the end

[1,2,3,4,5]
2
["N0","N1","N2","N4"]