1. Dummy before head
A dummy handles removing the head uniformly.
const dummy = { val: 0, next: head }Typorithm · medium
Step 1 of 8 · intro card
Linked Lists
Open an n-node gap between two pointers, then move both until slow sits before the target.
Removing the nth-from-end node naively needs the length first, a two-pass approach.
Advancing fast n steps ahead creates a fixed gap; when fast reaches the end, slow is just before the target.
A dummy node makes removing the head a non-special case.
Gap of n between fast and slow.
Stop when fast is at the last node.
Dummy handles head removal.
function removeNthFromEnd(head, n) {
const dummy = { val: 0, next: head };
let fast = dummy;
let slow = dummy;
for (let i = 0; i < n; i += 1) {
fast = fast.next;
}
while (fast.next !== null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}Connect each part of the code to the concept before you type.
A dummy handles removing the head uniformly.
const dummy = { val: 0, next: head }Advance fast n nodes ahead of slow.
for (let i = 0; i < n; i += 1)Move both until fast reaches the last node.
while (fast.next !== null)slow sits just before the node to remove.
slow.next = slow.next.nextdummy.next is the possibly-changed head.
return dummy.nextRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.