Search code examples
algorithmlinked-list

Remove Nth Node From End of List LeetCode


I'm doing the Remove Nth Node from End of List LeetCode challenge:

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

My code is failing on some test cases:

[1,2]
2

And I get this report:

Output [1]
Expected [2]

I've read the solutions already and it appears that my solution is the same as the one written, but I can't figure out where my mistake is. My code is as follows:

def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
    pointer1 = head
    pointer2 = head
    count = 0
    if not pointer1.next:
        return pointer1.next
    while pointer2 is not None:
        if count > n:
            pointer1 = pointer1.next
        pointer2 = pointer2.next
        count += 1
    pointer1.next = pointer1.next.next
    return head

I've been at this for half an hour now and I can't figure out hwo to fix it. Can someone please help?


Solution

  • Your solution will fail when n is equal to the number of nodes in the list. In that case you are supposed to remove the first node from the list, and by consequence you should return head.next.

    NB: the if you have before the while loop tests for a very specific instance of that case, i.e. when the list has just one element. But as explained above this action should apply in a more generic case than is identified in the if.

    So, the following if condition could be dropped:

    if not pointer1.next:
        return pointer1.next
    

    And add a condition after the while loop:

    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        pointer1 = head
        pointer2 = head
        count = 0
        while pointer2 is not None:
            if count > n:
                pointer1 = pointer1.next
            pointer2 = pointer2.next
            count += 1
        if count > n:
            pointer1.next = pointer1.next.next
            return head  
        else:
            return head.next