Why my python code is Time Limit exceed?


  • 0
    Y

    def removeElements(self,head,val):

        if head ==None:
            return None
        if head.next == None and head.val==val:
            return None;
        preNode = ListNode(-1)
        currentNode = ListNode(-1)
        preNode = currentNode = head
        while currentNode != None:
            if currentNode.val == val:
                preNode = currentNode.next
            else:
                preNode = currentNode
                currentNode = currentNode.next
        return head

  • 2
    M

    Check the line
    current = currentNode.next

    See if it is working for both if and else conditions. This is the most possible place where things can go wrong here to give you TLE.


  • 0
    Y

    Last executed input: [1,1], 1
    TLE for [1,1] , 1 Can you help me dear?


  • 0
    M

    Your currentNode does not reach the end of the list.

    Let's call it [1a,1b],1 (a and b to distinguish the first and second 1 in the list)

    Before while loop:

    preNode = 1a
    currentNode = 1a

    if condition satisfied because currentNode,1a == 1

    After first iteration of while:

    preNode = 1b
    currentNode = 1a <----- This is your error (if my python syntax is not rusty, haven't been on python for a while.. but check this out)

    if condition satisfied because currentNode,1a == 1

    After second iteration of while:

    preNode = 1b
    currentNode = 1a


  • 1
    M

    You can try understanding the flow from my code.

    Notice that you cannot return the old head because it will give you a wrong result if you were supposed to remove the head node.

    Here's my accepted solution in Python. Analyze the flow, draw a linked list on paper and iterate through each statement in the while loop, and mark pointer positions after every iteration and see how it works.

    This technique would help you solve many of the linked list problems. Feel free to reach out to me by replying to this post if you have further questions.

        if head == None:
            return None;
        c = head;
        p = None;
        nH = None;
        while c != None:
            if c.val != val:
                if nH == None:
                    nH = c;
                else:
                    p.next = c;
                p = c;
            c = c.next;
        if p != None:
            p.next = None;
        return nH

  • 0
    Y

    3Q very much my friend!


  • 0
    Y

    3Q u are hot mind, Thank u very much


Log in to reply
 

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