I wanted to ask your opinion, why below code gets Time Limit Exceeded error ?


  • 0
    O

    Hello,
    I wanted to ask your opinion, why below code gets Time Limit Exceeded error, although there is no constraint in the Definition of the Problem that it must run fast for the short lists.
    My solution should work for short and Long lists.
    Thanks for your Feedback.

    '''
    class Solution {
    public:
    ListNode *detectCycle(ListNode *head) {

        ListNode *tmpHead = head;
        ListNode *tmpNext = NULL;
        
        while(tmpHead!=NULL)
        {
            tmpNext = tmpHead->next;
            while(tmpNext!=NULL)
            {
                if(tmpHead==tmpNext)
                    return tmpHead;
                else
                    tmpNext = tmpNext->next;
            }
            tmpHead=tmpHead->next;
        }
        return NULL;
    }
    

    };
    '''


  • 0
    M

    The inside while loop will run for ever. Consider the following linked list:

    1->2->3->4->2

    Your tmpNext node will start from 2 then go to 3 ->4 and then back to 2.


Log in to reply
 

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