Linked List · Pattern 3 of 5
Front and back pointers: the n-th node from the end
Move a front pointer n steps ahead, then move both pointers together. When the front one hits the end, the back one is exactly n nodes from the end, in a single pass.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The n-th or k-th node counted from the end
- One pass only, and you do not know the length
- Remove or change a node near the tail
The template
ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head; // the head itself may be removed
ListNode front = dummy, back = dummy;
for (int i = 0; i < n; i++) front = front.next; // open a gap of n
while (front.next != null) { // move both until front is the last node
front = front.next;
back = back.next;
}
back.next = back.next.next; // back sits just before the target
return dummy.next;
} def remove_nth_from_end(head, n):
dummy = ListNode(0, head) # the head itself may be removed
front = back = dummy
for _ in range(n): # open a gap of n
front = front.next
while front.next: # move both until front is the last node
front, back = front.next, back.next
back.next = back.next.next # back sits just before the target
return dummy.next ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy(0);
dummy.next = head; // the head itself may be removed
ListNode *front = &dummy, *back = &dummy;
for (int i = 0; i < n; i++) front = front->next; // open a gap of n
while (front->next) { // move both until front is the last node
front = front->next;
back = back->next;
}
back->next = back->next->next; // back sits just before the target
return dummy.next;
} function removeNthFromEnd(head, n) {
const dummy = new ListNode(0, head); // the head itself may be removed
let front = dummy, back = dummy;
for (let i = 0; i < n; i++) front = front.next; // open a gap of n
while (front.next) { // move both until front is the last node
front = front.next;
back = back.next;
}
back.next = back.next.next; // back sits just before the target
return dummy.next;
} The variations
-
1A fixed gap between two pointers
The distance between the pointers never changes, so when the front one reaches the end the back one is n from the end. Start both at a dummy so the back one stops on the node before the one to remove.
Mistakes to avoid
- Starting both pointers at the head instead of a dummy: removing the head (n equal to the length) then breaks.
- An off-by-one gap: to stop before the target,
backmust trail the last node by exactly n. - Counting the length first and walking again works, but it is two passes when the question asks for one.
Lesson done
Next: In-place reversal: prev, curr and next →Mark it done once you can write the template from memory and you have solved the worked examples yourself.