# 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;
}

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://private-26.gitbook.io/notes/coding/medium/19.-remove-nth-node-from-end-of-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
