Remove the Nth Node From the End of a Linked List
Implement removeNthFromEnd
Given the
head of a singly linked list and an integer n, remove the nth node from the end of the list (1-indexed) and return the new head.
The tricky part isn't finding the node to remove — it's finding the node just before it, since deletion means rewiring a next pointer, and a singly linked list can't look backward on its own. The optimal solution handles this in one pass with the same head startHead Start (n-Gap) TechniqueAdvance one pointer n steps before starting the second one. The n-node gap between them stays constant as both move together, so when the leading pointer reaches the last node, the trailing pointer sits exactly at the predecessor of the nth-from-end node. technique used for finding the kth node from the end: let fast move n steps ahead, then walk both together until fast.next is null — slow lands exactly where it needs to snip. The one edge case is n equaling the list's length, which means the head itself must go.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 2
Output: [2]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in head ≤ 10⁴ - ●
-10⁹ ≤ node value ≤ 10⁹ - ●
n is 1-indexed from the end, and 1 ≤ n ≤ number of nodes
head =
[1, 2, 3, 4, 5]
n =
2