InterviewHubPRO
Section Overview
Q40

Question 40 of 100

Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

40%
DSA Patterns (Multi-Lang)•Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

Remove Nth Node From End of List.

In Simple Words: Advance fast pointer by $N+1$ steps from dummy head. Then move slow and fast together until fast === null. slow.next is now exactly the Nth node from end to delete.

  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def removeNthFromEnd(head: ListNode | None, n: int) -> ListNode | None:
    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