← DSA
MEDIUM

Remove Nth Node From End of List

PracticeNeetCode ↗LeetCode ↗

Given the head of a linked list, remove the nth node from the end of the list and return the head.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Create a dummy node pointing to head; set slow = dummy, fast = dummy.
  2. Advance fast n + 1 steps ahead of slow.
  3. Move slow and fast together, one step at a time, until fast is None.
  4. Unlink the target node with slow.next = slow.next.next, then return dummy.next.

Complexity

Time: O(n) — Space: O(1)

Code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
    dummy = ListNode(0, head)
    slow = fast = dummy

    for _ in range(n + 1):
        fast = fast.next

    while fast:
        slow = slow.next
        fast = fast.next

    slow.next = slow.next.next
    return dummy.next

Code Explanation

How the solution above works, piece by piece.

  1. dummy = ListNode(0, head) sits before the head, so removing the first node works the same as any other.
  2. Move fast n + 1 steps: now there are exactly n nodes between slow and fast.
  3. Move both one step at a time until fast is None. The gap is preserved, so slow stops just before the n-th node from the end.
  4. slow.next = slow.next.next unlinks it.
  5. Return dummy.next (the head may have changed). One pass: O(length) time, O(1) space.

Visual Walkthrough

Running it on head = [1, 2, 3, 4, 5], n = 2:

Removing the 2nd node from the end with a gap of n + 1start: slow = fast = dummy (d)d12345Noneslow·fastfast moves n + 1 = 3 steps aheadd12345Noneslowfastmove both until fast is Noned12345None ← fastslowslow.next = slow.next.next skips 41235None
Keeping fast exactly n + 1 nodes ahead means that when fast falls off the end, slow is right before the node to delete. The dummy node (d) handles deleting the real head with no special case.
slowfast

Video Explanation

NeetCode — Oracle Interview Question, LeetCode 19