LeetCode 19: Remove Nth Node From End of List — Python Solution

LeetCode 19: Remove Nth Node From End of List is a Medium linked list problem. This Python walkthrough develops a fixed-gap pointers solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicLinked List
Reusable patternfixed-gap pointers
ComplexityO(n) time and O(1) extra space

Recognizing the pattern

Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.

For this problem specifically, advance fast n steps from a dummy node, then move fast and slow together until fast reaches the end; slow precedes the target. The invariant worth writing beside the code is: The pointers remain n nodes apart, so the slow pointer stops immediately before the nth node from the end.

Step-by-step algorithm

  1. Identify the input state consumed by removeNthFromEnd(head, n) and initialize the data required by the fixed-gap pointers pattern.
  2. Advance fast n steps from a dummy node, then move fast and slow together until fast reaches the end; slow precedes the target.
  3. After each update, verify the page’s central invariant: The pointers remain n nodes apart, so the slow pointer stops immediately before the nth node from the end.
  4. Finish only after the boundary behavior is covered: The dummy node handles removing the original head.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def removeNthFromEnd(self, head, n):
        dummy = ListNode(0, head)
        fast = slow = dummy
        for _ in range(n):
            fast = fast.next
        while fast.next:
            fast, slow = fast.next, slow.next
        slow.next = slow.next.next
        return dummy.next

Reading the implementation

The main entry point is removeNthFromEnd(head, n). The named working state includes dummy, fast; those variables make the fixed-gap pointers state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, advance fast n steps from a dummy node, then move fast and slow together until fast reaches the end; slow precedes the target.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Advance fast n steps from a dummy node, then move fast and slow together until fast reaches the end; slow precedes the target. Each update records the current item without invalidating earlier decisions; consequently, the pointers remain n nodes apart, so the slow pointer stops immediately before the nth node from the end.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert listed(Solution().removeNthFromEnd(linked([1,2,3,4,5]),2)) == [1,2,3,5]

Common mistakes and edge cases

  • Problem-specific boundary: The dummy node handles removing the original head.
  • Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
  • Invariant check: after every update, confirm that the pointers remain n nodes apart, so the slow pointer stops immediately before the nth node from the end.

Interview review checklist

  • Explain why fixed-gap pointers matches the structure of this input.
  • State the invariant in one sentence before tracing code: The pointers remain n nodes apart, so the slow pointer stops immediately before the nth node from the end.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: The dummy node handles removing the original head.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 25. Reverse Nodes in k-Group · Next: 82. Remove Duplicates from Sorted List II