LeetCode #19 Medium

Remove Nth Node From End of List

Remove Nth Node From End of List is LeetCode 19 (Medium). Given the head of a linked list and a number n, remove the node that is n-th counting from the end (the last node is 1st from the end) and return the head.

  • n is always valid: it is between 1 and the number of nodes, so the node to remove exists.
  • When n equals the length, the node to remove is the head.
  • The follow-up asks for one pass over the list.
Constraints
  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz
linked-listtwo-pointers
Open on LeetCode ↗
02

Intuition

A singly linked list cannot be read backwards, but a distance can be measured forwards. Two pointers kept a fixed number of links apart stay that far apart all the way to the end. If the front pointer reaches the end (null) while the back pointer is n + 1 links behind it, the back pointer is standing on the node just before the one to delete.

Starting both pointers on a dummy node in front of the head means that "node before the target" always exists, even when the target is the head.

How to spot this pattern

"k-th from the end" in a singly linked list, with a one-pass follow-up, is the fixed-gap two-pointer pattern.

03

Approach

Try it first

Before reading on, decide how many links ahead the front pointer must start so the back pointer stops on the node before the target, not on the target. Check your count on a one-node list with n = 1. Aim for one pass and O(1) extra space.

1

Put both pointers on a dummy node

Create dummy with dummy.next = head, and set fast and slow to it. The dummy is the node before the head, which is exactly where slow must stop when the head is the one removed.

2

Open a gap of n + 1 links

Move fast forward n + 1 times. Now fast is n + 1 links ahead of slow; it may already be null when n is the length of the list.

3

Walk both until fast is null

Step fast and slow together until fast is null. The gap never changes, so slow ends n + 1 links before the end of the list: one node before the n-th node from the end.

4

Unlink the target

Set slow.next = slow.next.next and return dummy.next. Returning the dummy's next, not head, gives the right answer when the old head was removed.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
▶3 dummy = ListNode(0, head)
▶4 fast = slow = dummy
▶5 for _ in range(n + 1):
▶6 fast = fast.next
▶7 while fast:
▶8 fast = fast.next
▶9 slow = slow.next
▶10 slow.next = slow.next.next
▶11 return dummy.next
start12345nullbothboth start on the placeholder; target: 2nd from the end
n2
faststart
slowstart
The placeholder is the node before the head. If the head turns out to be the target, slow can stop here and still have a link to change.
start12345nullfastslow1 link apartfast moves ahead alone (1 of 3)
fast1
gap1
fast needs a lead of n + 1 = 3 links. One link per step, slow waits.
start12345nullfastslow2 links apartfast moves ahead alone (2 of 3)
fast2
gap2
fast needs a lead of n + 1 = 3 links. One link per step, slow waits.
start12345nullfastslow3 links apartfast moves ahead alone (3 of 3)
fast3
gap3
The lead is now n + 1 = 3. One more than n, so slow will stop on the node before the target, not on the target.
start12345nullfastslow3 links apartboth step; still 3 links apart
fast4
slow1
Moving both keeps the distance fixed. Whatever fast's distance from the end is, slow's is always 3 more.
start12345nullfastslow3 links apartboth step; still 3 links apart
fast5
slow2
Moving both keeps the distance fixed. Whatever fast's distance from the end is, slow's is always 3 more.
start12345nullfastslow3 links apartfast fell off the end → slow is just before the target
fastnull
slow3
fast has fallen off the end. slow is 3 links behind null, so the node after slow is the 2nd from the end.
start12345nullfastslow3 now skips 4 and points to 5
removed4
One link change: slow's next skips the target and lands on the node after it.
start12345nullreturn 1 → 2 → 3 → 5
return1
The head did not change here, but returning the placeholder's next node is what makes the head case work with the same code.
05

Count the length, then walk

The first pass counts the nodes, sz. The node to delete is then number sz − n + 1 from the front, so the node before it is sz − n steps after a dummy placed in front of the head. The dummy again covers the case n = sz.

▶1class Solution:
▶2 def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
▶3 size = 0
▶4 node = head
▶5 while node:
▶6 size += 1
▶7 node = node.next
▶8 dummy = ListNode(0, head)
▶9 prev = dummy
▶10 for _ in range(size - n):
▶11 prev = prev.next
▶12 prev.next = prev.next.next
▶13 return dummy.next
06

Common pitfalls

Opening a gap of n instead of n + 1

✗ Wrong
for _ in range(n):
    fast = fast.next
✓ Right
for _ in range(n + 1):
    fast = fast.next

With a gap of n, slow stops on the target itself, and slow.next = slow.next.next removes the node after it. For [1, 2, 3, 4, 5] with n = 2 that deletes 5 instead of 4.

Starting the pointers on head instead of a dummy

✗ Wrong
fast = slow = head
✓ Right
dummy = ListNode(0, head)
fast = slow = dummy

For [1, 2] with n = 2 the head must go, but no node sits before it. Moving fast three links from the head runs off the end and crashes on a null pointer.

07

Edge cases

One node, n = 1

fast moves dummy → 1 → null, the walk loop never runs, and slow (the dummy) unlinks the only node. The answer is an empty list.

n = 1 on a longer list

The last node is removed. slow stops on the second-to-last node and its link becomes null.

08

Complexity

Time
O(sz)
Space
O(1)
fast moves sz + 1 times in total and slow fewer, so each node is read once by each pointer. Only the dummy and two pointers are extra.
09

Remove Nth Node From End of List FAQ

Does the one-pass version actually do less work?

Not much: two pointers each walk most of the list, about as many steps as counting and walking again. What it saves is a second read of the list, which matters only when the list can be read once.

Can recursion find the n-th node from the end?

Yes. Recurse to the end, and on the way back return how many nodes lie after the current one. The node that sees exactly n nodes after itself unlinks its next; start the recursion from a dummy so the head case works. It is one pass too, but it uses a stack frame per node.