← Back to Leo Academy Masterclass

Problem #19: Remove Nth Node From End of List

Medium Linked List

Intuition & Strategy Breakdown

Use two pointers (fast and slow) separated by N nodes. Move both pointers forward until fast reaches the end; slow will then point to the node immediately before the target node to delete.

Python Solution

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        left = dummy
        right = head
        while n > 0 and right:
            right = right.next
            n -= 1
        while right:
            left = left.next
            right = right.next
        left.next = left.next.next
        return dummy.next

Java Solution

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode left = dummy, right = head;
        while (n > 0 && right != null) {
            right = right.next;
            n--;
        }
        while (right != null) {
            left = left.next;
            right = right.next;
        }
        left.next = left.next.next;
        return dummy.next;
    }
}
Watch Interactive Video on Leo Academy Main App