Skip to content
DSA Patterns
Menu
Language
Fast & Slow PointersLC #191 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Remove Nth Node From End of List

Problem (restated)

Given the head of a singly linked list, remove the nth node from the end and return the head.

Intuition

Maintain a gap of n between two pointers. When the leader hits null, the follower sits just before the node to delete. A dummy head simplifies deleting the first node.

Approaches

Dummy + gap of n

Unverified
Time O(n)Space O(1)

Idea. dummy→head. Advance fast n+1 steps from dummy, then move fast and slow together until fast is null. slow.next = slow.next.next.

Walkthrough. List 1→2→3→4→5, n=2. After gap, remove 4.

Trade-offs. One pass, O(1) space. Two-pass (compute length first) is clearer but slightly more code.

Solution
Show helper code
class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) {
    this.val = val; this.next = next;
  }
}
class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val = 0, next: ListNode | null = null) {
    this.val = val; this.next = next;
  }
}
export function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
  const dummy = new ListNode(0, head);
  let fast: ListNode | null = dummy;
  let slow: ListNode | null = dummy;
  for (let i = 0; i < n + 1; i++) fast = fast!.next;
  while (fast) { fast = fast.next; slow = slow!.next; }
  slow!.next = slow!.next!.next;
  return dummy.next;
}
export function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
  const dummy = new ListNode(0, head);
  let fast: ListNode | null = dummy;
  let slow: ListNode | null = dummy;
  for (let i = 0; i < n + 1; i++) fast = fast!.next;
  while (fast) { fast = fast.next; slow = slow!.next; }
  slow!.next = slow!.next!.next;
  return dummy.next;
}

Template connection

A dummy sits in front of the head. fast walks n steps ahead of slow, then both walk until fast falls off. slow.next is the node to delete. When n is the whole length, that node is the original head.

Reflection

  • The nth node from the end is two pointers a fixed gap apart. Why does a dummy make deleting the head the same path as any other node?
  • n equal to the length deletes the head. n = 1 deletes the tail. Which fast/dummy walk covers both?
  • Counting the length and walking again is also O(n). Why does the interview still want one pass?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Remove the 2nd node from the end. Dummy head plus a gap of n.

D
1
2
3
4
5

n = 2

Key:CurrentActive rangeLeft / slowRight / fastMatchSettledEliminated