> For the complete documentation index, see [llms.txt](https://private-26.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://private-26.gitbook.io/notes/coding/medium/19.-remove-nth-node-from-end-of-list.md).

# 19. Remove Nth Node From End of List

## Intuition

To remove the **nth node from the end**, we can use the **two-pointer technique**. By moving one pointer `n` steps ahead, we create a gap of `n` nodes between two pointers. When the first pointer reaches the end, the second pointer will be just before the node to remove.

## Complexity

| Space Complexity | Time Complexity |
| ---------------- | --------------- |
| $$\text{O}(1)$$  | $$\text{O}(N)$$ |

## Code

```java
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;
}

```
