Python solution with detailed explanation

  • 0


    Remove Nth Node From End of List

    Fast and Slow Pointer

    • slow is head and fast is moved N units from head. The idea is that after we move both by 1 until is None, we will have slow pointing to the previous node that has to be deleted.
    • But there is one boundary condition: If N == size of the list, then head needs to be chopped off. Test that condition.
    class Solution(object):
        def removeNthFromEnd(self, head, n):
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            if head == None:
                return None
            n1, n2 = head, head
            for _ in range(n):
                n2 =
            if n2 == None:
                head, =, None
                return head
                n1, n2 =,
            temp =
   = None
            return head

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.