Overview
Given the head of a linked list, remove the nth node from the end of the list and return the modified list's head.
Use a one-pass algorithm with O(1) extra space.
Constraints
- The number of nodes is in range
[1, 30]. 1 <= n <= length of list.- Node values are integers.
Examples
// List: 1->2->3->4->5, n=2 removeNthFromEnd(head, 2); // => 1->2->3->5 (removed node 4)
// List: 1, n=1 removeNthFromEnd(head, 1); // => null (removed the only node) // List: 1->2, n=1 removeNthFromEnd(head, 1); // => 1 (removed node 2)
Solution
Reveal solution
function removeNthFromEnd(head, n) {
const dummy = { val: 0, next: head };
let fast = dummy;
let slow = dummy;
// Advance fast by n+1 steps
for (let i = 0; i <= n; i++) {
fast = fast.next;
}
// Move both until fast reaches end
while (fast) {
fast = fast.next;
slow = slow.next;
}
// Skip the target node
slow.next = slow.next.next;
return dummy.next;
}Two-pointer technique: fast pointer leads by n+1 nodes. When fast reaches null, slow is right before the target.
Resources
delete-nth-node-from-end.js
Delete Nth Node from End of Linked List
hardcodingAlgorithmsLinked Lists
Overview
Given the head of a linked list, remove the nth node from the end of the list and return the modified list's head.
Use a one-pass algorithm with O(1) extra space.
Constraints
- The number of nodes is in range
[1, 30]. 1 <= n <= length of list.- Node values are integers.
Examples
// List: 1->2->3->4->5, n=2 removeNthFromEnd(head, 2); // => 1->2->3->5 (removed node 4)
// List: 1, n=1 removeNthFromEnd(head, 1); // => null (removed the only node) // List: 1->2, n=1 removeNthFromEnd(head, 1); // => 1 (removed node 2)
Solution
Reveal solution
function removeNthFromEnd(head, n) {
const dummy = { val: 0, next: head };
let fast = dummy;
let slow = dummy;
// Advance fast by n+1 steps
for (let i = 0; i <= n; i++) {
fast = fast.next;
}
// Move both until fast reaches end
while (fast) {
fast = fast.next;
slow = slow.next;
}
// Skip the target node
slow.next = slow.next.next;
return dummy.next;
}Two-pointer technique: fast pointer leads by n+1 nodes. When fast reaches null, slow is right before the target.
Resources
NameTopicDifficulty
103 of 103 problems