#19
Medium Algorithms Remove nth node from end of list
Linked List Two Pointers
51.0% acceptance
Jan 12, 2026
21109
899
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
let mut dummy = Box::new(ListNode { val: 0, next: head });
let mut fast = &dummy.clone();
// Move fast pointer n steps ahead
for _ in 0..n {
fast = fast.next.as_ref().unwrap();
}
// Move both pointers until fast reaches the end
let mut slow = &mut dummy;
while fast.next.is_some() {
fast = fast.next.as_ref().unwrap();
slow = slow.next.as_mut().unwrap();
}
// Remove the nth node from end
let next = slow.next.as_mut().unwrap().next.take();
slow.next = next;
dummy.next
}
}