Curious why my Python Solution Ran so Quickly


  • -1
    G
    def removeNthFromEnd(self, head, n):
            current = head
            # To remove the last element, you need to alter the element before it, so must be a separate case
            if n == 1:
                # If the linked list is only one element long, we just return None
                if current.next == None:
                    return None
                while current.next.next != None:
                    current = current.next
                current.next = None
                return head
            # For this part, we keep track of two pointers
            # One stays n steps behind so when the first hits the end, it lies on the node we want to remove
            toRemove = head
            while current.next != None:
                if n == 1:
                    toRemove = toRemove.next
                else:
                    n -= 1
                current = current.next
            # Since this isnt the last node, we just set its values to the values of its next
            toRemove.val, toRemove.next = toRemove.next.val, toRemove.next.next
            return head
    

    This ran in 85 ms reliably which on the chart appeared below pretty much all other python solutions. Is this just random or is this solution really faster than almost everyones? (Seems unlikely)


  • 0
    T

    This is because of the recent update to LeetCode. Everyone's code is running faster than before now.


Log in to reply
 

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