TypeScript | Memory beats 99.66% [EXPLAINED]
Intuition\nTo remove the nth node from the end of the linked list, I need to figure out how to find this node efficiently. Instead of first calculating the leng
# Intuition\nTo remove the nth node from the end of the linked list, I need to figure out how to find this node efficiently. Instead of first calculating the length of the list and then finding the node, I\u2019ll use a two-pointer technique to keep track of the node to be removed while traversing the list.\n\n# Approach\nDummy Node: Add a dummy node to simplify edge cases.\n\nTwo Pointers: Move the first pointer n+1 steps ahead. Then, move both first and second pointers together until first reaches the end.\n\nRemove Node: The second pointer will be just before the target node; adjust its next pointer to remove the target node.\n\n# Complexity\n- Time complexity:\nO(L), where L is the length of the list, since I traverse the list once.\n\n- Space complexity:\nO(1), because I only use a few extra pointers.\n\n# Code\n```typescript []\n// We assume ListNode is provided by the environment and should not be redefined.\n\nfunction removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {\n    // Create a dummy node to simplify edge cases\n    const dummy = new ListNode(0);\n    dummy.next = head;\n    let first: ListNode | null = dummy;\n    let second: ListNode | null = dummy;\n\n    // Move the first pointer n+1 steps ahead\n    for (let i = 0; i <= n; i++) {\n        first = first?.next ?? null;\n    }\n\n    // Move both pointers until the first pointer reaches the end\n    while (first !== null) {\n        first = first.next;\n        second = second?.next ?? null;\n    }\n\n    // Remove the nth node from the end\n    second!.next = second?.next?.next ?? null;\n\n    // Return the new head of the list\n    return dummy.next;\n}\n\n```
['TypeScript']