CodeArchon

mediumLinked ListAmazonMeta

Dropkick From Tail

A queue of waiting tickets is linked front-to-back. Remove the nth-from-last ticket in one pass.

Given the head of a linked list and integer n, remove the nth node from the end and return the (possibly new) head.

Choose approach

1
2
3
4
5
nil
fastslow
1/7
Narrationstep 1 of 7

Two cursors from a dummy head. Advance fast 2 steps so there's exactly 2 nodes between fast and slow.

1def dropkick_from_tail(head, n: int):
2 dummy = ListNode(0, head)
3 fast = slow = dummy
4 for _ in range(n):
5 fast = fast.next
6 while fast.next:
7 fast, slow = fast.next, slow.next
8 slow.next = slow.next.next
9 return dummy.next
Variables
n=2

How to think about it

  1. The gap between slow and fast is the invariant: n nodes.
  2. A dummy head unifies the "remove head" case.
  3. Walk the pair together until fast.next is null.
  4. Splice: slow.next = slow.next.next.

Edge cases to catch in interview

  • Removing the head → dummy helps.
  • Single node → removing it yields empty.
  • n equal to length — removes head.

Examples

Example 1[1,2,3,5]
{"values":[1,2,3,4,5],"n":2}
Example 2[]
{"values":[1],"n":1}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed