Why did I get time limit exceeded? Why do we have to use two pointer algorithms

  • 0
    bool hasCycle(ListNode *head) {
        if (head == NULL){
            return false;
        ListNode* temp = head->next;
        while(temp != NULL && temp != head){
        return (temp == head);

  • 1

    You have an infinite loop in the while() loop. You will never advance 'temp' if you have two or more elements.

    There are other viable solutions than the two pointer method. A "visited" array, a for() loop on all elements.

Log in to reply

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