Remove Nth Node From End

35 min · removeNthFromEnd()

The instruction points backward — “remove the third node from the end” — but every link in the list points forward. You need to translate that request into a node you can reach.

A singly linked list is a chain of nodes where each node links only to the next one. Given a non-empty list and an integer n, remove the node that sits n positions from the end and return the resulting head. Counting is 1-indexed from the end, so n = 1 means the tail.

A few ground rules:

  • n is always valid for the supplied list.
  • If n equals the list length, remove the head.
  • Removing the list's only node returns an empty list.
  • Keep every surviving node in its original order.

Constraints

  • 1 <= list length L <= 10_000
  • 1 <= n <= L
  • -1_000_000_000 <= Node.val <= 1_000_000_000

Hints

Translate end to front

If the list length is L, the node to remove has zero-based index L - n from the front. Measuring the length first gives you a clean two-walk solution.

Give the head a predecessor

A dummy node before head means even the real head has a previous node. Then every removal uses the same link change: previous.next = previous.next.next.

Keep a fixed gap

Start two pointers at the dummy node and move fast forward n times. Move both until fast reaches the tail; slow will be just before the node to remove.

Follow-up

Can you remove the correct node in one traversal without storing the list's nodes in an array?

Visible cases

Examples

Example 1

ready
Input
head = [
  1,
  2,
  3,
  4,
  5
]
n = 2
Expected
[
  1,
  2,
  3,
  5
]
Why
the second node from the end holds 4

Example 2

ready
Input
head = [
  1
]
n = 1
Expected
[]
Why
removing the only node leaves an empty list

Example 3

ready
Input
head = [
  1,
  2
]
n = 1
Expected
[
  1
]
Why
n = 1 removes the tail

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite