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.

1 variation · 1 problem · 1 with animated walkthroughs

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

Front Back Pointer
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;
}

The variations

  1. 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, back must 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.
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.