Remove Nth Node From End of List

Difficulty: Medium

Given the head of a linked list and a number n, remove the nth node from the end (n = 1 means the last node) and return the head.

Try to do it in one pass.

Examples

Input: head = [1, 2, 3, 4, 5], n = 2
Output: [1, 2, 3, 5]

The 2nd node from the end is the one with value 4.

Input: head = [1], n = 1
Output: []

Input: head = [1, 2], n = 1
Output: [1]

Constraints

  • The number of nodes is between 1 and 30.

  • 0 <= Node.val <= 100

  • 1 <= n <= number of nodes in the list

Approach

If you first count the list's length, "n from the end" becomes a fixed position from the front: walk to just before it and unlink the next node. That works, but takes two passes.

To do it in one pass, move a "fast" pointer n steps ahead, then move both pointers one step at a time. When fast reaches the end, the gap leaves the slow pointer exactly one node before the one to remove.

Solutions

Brute Force — Two Passes (Count, Then Remove)

Walk the list once to count its nodes, which tells you how far from the front the target is. Walk again to that position and unlink the node. A dummy node before the head means removing the first node needs no special case.

class ListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

function removeNthFromEnd(head, n) {
  let length = 0;
  let curr = head;
  while (curr) {
    length++;
    curr = curr.next;
  }

  const dummy = new ListNode(0, head);
  let prev = dummy;
  for (let i = 0; i < length - n; i++) {
    prev = prev.next;
  }

  prev.next = prev.next.next;
  return dummy.next;
}

Time: O(n) — two passes over the list · Space: O(1)

Optimal — One Pass with a Gap

Put a dummy node in front of the head so removing the head needs no special case. Start "fast" and "slow" at the dummy, and move fast n steps ahead. Then move both together until fast reaches the last node. Thanks to the n-node gap, slow is now one node before the target, so unlink it.

class ListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

function removeNthFromEnd(head, n) {
  const dummy = new ListNode(0, head);
  let fast = dummy;
  let slow = dummy;

  for (let i = 0; i < n; i++) {
    fast = fast.next;
  }

  while (fast.next) {
    fast = fast.next;
    slow = slow.next;
  }

  slow.next = slow.next.next;
  return dummy.next;
}

Time: O(n) · Space: O(1)