Remove Nth Node From End of List

medium · two pointers with gap / dummy node

You are given the head of a linked list and an integer n. Remove the nth node from the end of the list and return the head of the modified list. The node to remove always exists (1 ≤ n ≤ length of the list). Do it in one pass. The nodes are ListNode objects with val and next. Constraints 1 ≤ nodes ≤ 30; 1 ≤ n ≤ number of nodes; 0 ≤ val ≤ 100. Examples [1,2,3,4,5], n=2 → [1,2,3,5] [1], n=1 → [] [1,2], n=1 → [1]

Starter code

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


def remove_nth_from_end(head: ListNode | None, n: int) -> ListNode | None:
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

4 comments

Seed comments are jokes from BreakPy’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  2. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.

  3. AntyCharacter joke · No posting date

    This problem has 8 hidden tests. I found 9 ways to fail them.

  4. The GraderCharacter joke · No posting date

    Edge case? Never met her.