Remove Nth Node From End of List
Remove the nth node from the end of a linked list and return the head.
Example: head = [1,2,3,4,5], n = 2 → [1,2,3,5]
Sample Input
—
Sample Output
—
Constraints
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
Topics
Two Pointer (Gap of n)
function removeNthFromEnd(head, n) {
const dummy = {next: head};
let fast = dummy, slow = dummy;
for (let i = 0; i <= n; i++) fast = fast.next;
while (fast) { fast = fast.next; slow = slow.next; }
slow.next = slow.next.next;
return dummy.next;
}
Time: O(L) | Space: O(1)
Saved in this browser only. Private to you.