19. Remove Nth Node From End of List
Intuition
Complexity
Space Complexity
Time Complexity
Code
public ListNode removeNthFromEnd(ListNode head, int n) {
// Two pointers both starting at the head
ListNode trailingPointer = head;
ListNode leadingPointer = head;
// Move the leading pointer 'n' steps ahead
while (leadingPointer.next != null) {
if (n <= 0) {
// Start moving the trailing pointer after the leading one is 'n' steps ahead
trailingPointer = trailingPointer.next;
}
// Advance the leading pointer and decrease the gap
leadingPointer = leadingPointer.next;
n--;
}
// If 'n' is still greater than 0, that means we need to remove the head node
if (n > 0) {
return head.next;
}
// Skip the target node
trailingPointer.next = trailingPointer.next.next;
// Return the updated list head
return head;
}
Last updated