All coding questions

Remove Nth Node From End of List

medium
NeetCode 150linked-listtwo-pointers

Problem

Given the head of a singly linked list and a number n, remove the nth node counting from the end and return the head. Do it in a single pass.

Examples

Input: 1 -> 2 -> 3 -> 4 -> 5, n = 2
Output: 1 -> 2 -> 3 -> 5
The second-from-last node, value 4, is removed.
Input: 1, n = 1
Output: empty list
Removing the only node empties the list.

Constraints

  • 1 <= number of nodes <= 30
  • 1 <= n <= number of nodes
Hints(tap to reveal)
  • 1. A gap of n between two pointers locates the target.
  • 2. A dummy head handles removing the first node.
Optimal approach(spoiler)
  1. Use a dummy node before the head and two pointers starting there.
  2. Advance the lead pointer n+1 steps ahead.
  3. Move both pointers until the lead reaches the end.
  4. The trailing pointer now sits just before the node to remove; relink past it.
  5. O(n) single pass, O(1) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor