Skip to problem
←

Remove Nth Node From End of List

Medium 0 attempts

Given a nonempty singly linked list and an integer n, remove exactly the nth node from the end, counting from 1, and return the new head.

The last node is position 1 from the end. If n equals the list length, remove the head. The input guarantees a valid n.

Remove by position, not by value. Keep every other original node in its original order without changing values or creating replacement nodes. Return null when removing the only node.

For [1, 2, 3, 4, 5] and n = 2, remove node 4 to obtain [1, 2, 3, 5]. Your function receives nodes with val and next properties; examples show value arrays.

Follow-up: Solve it in one forward pass using constant extra space.

Function contract

Implement removeNthFromEnd(head, n). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head after removing exactly the nth original node from the end. Retain all other original nodes in order; return null if the list becomes empty.

Example 1

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

Example 2

Input
head = [1]
n = 1
Output
[]
Constraints
  • 1 <= number of nodes <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= number of nodes

Two Pointers with a Fixed Gap

Place a dummy node before the head and start both pointers there. Move fast forward n + 1 links, then advance both pointers together until fast reaches null.

The maintained gap puts slow immediately before the node to delete. Bypass that node with slow.next = slow.next.next. The dummy handles deleting the head without a separate branch, including the single-node case.

The loop deliberately advances n + 1 times, not n: the slow pointer must stop at the predecessor. The valid-n guarantee makes all initial advances safe.

javascript
function removeNthFromEnd(head, n) {
  const dummy = { next: head };
  let fast = dummy,
    slow = dummy;
  for (let i = 0; i <= n; i++) fast = fast.next;
  while (fast) {
    fast = fast.next;
    slow = slow.next;
  }
  slow.next = slow.next.next;
  return dummy.next;
}

Time: O(L) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript