Task example: Remove Nth Node From End of List

Remove the node at position n when counting from the tail, starting at 1. Return the head of the remaining chain. Keep the surviving nodes in their original order; the result may be empty.

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

Array notation represents node values. The editor supplies ListNode with val and next. The inputs are a nonempty head node and a valid n, not an array passed to your function.

LeetCode 19
01 / Count & remove - two passes

Count & remove: video explanation

head = [1,2,3,4,5], n = 2
result = [1,2,3,5]

Prefer reading? Follow the steps below.

  1. Add a dummy node before head and count all L nodes. Dummy gives the first node a predecessor, so removing the head needs no special branch.
  2. Start prev at dummy and move L - n links. With five nodes and n = 2, move three times to node 3, immediately before the target.
  3. Set prev.next = prev.next.next to bypass one node. Return dummy.next: it points to the new head, or None if the only node was removed.

Time complexity · O(L)

Counting takes L steps and the second walk takes L - n steps. At most 2L steps means O(L) time, not O(L²).

Space complexity · O(1)

One dummy node, a counter, and a fixed number of references use O(1) extra space.

PYTHONLive code trace
02 / Two pointers - one pass

Two pointers: video explanation

head = [1,2,3,4,5], n = 2
result = [1,2,3,5]

Prefer reading? Follow the steps below.

  1. Start slow and fast at dummy. Advance fast n links, leaving exactly n links between the pointers.
  2. While fast.next exists, move both pointers one link. When fast reaches the tail, slow is directly before the target. Stop at the tail, not after it.
  3. Set slow.next = slow.next.next and return dummy.next. This also handles removing the head, tail, or only node.

Both approaches use O(L) time and O(1) extra space. The fixed gap finds the predecessor without counting the list and starting again.

Time complexity · O(L)

Fast advances L links in total; slow advances L - n links. Each move does constant work, so time complexity is O(L).

Space complexity · O(1)

Only two moving references and one dummy node are needed: O(1) extra space.

PYTHONLive code trace

Remove Nth Node From End · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.