# Why is this C solution "Time Limit Exceeded"?

• ``````/**
* Make every node points back to its predecessor while iterating forward,
* so if there is a cycle, it will iterate back to head
*/
{
return 0;

return 1;

struct ListNode* p2 = p1->next;
struct ListNode* p3 = p2->next;

while (p3 != NULL && p3 != head) {
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}

}
``````

Always throws "Time Limit Exceeded" on this test

``````[-1,-7,7,-4,19,6,-9,-5,-2,-5]
tail connects to node index 6
``````

It executes only 0.1ms on tutorialspoint.com online C compiler.

• This post is deleted!

• @vicch7 i do the same thing by python a month ago, and passed all test casts. the faster algorithm is o(n), but this method would be o(2n). maybe it caused the TLE.
By the way, if you do not want to destroy the List, it's better to inverse it again.

• @dyungwang

If you do not want to destroy the List, it's better to inverse it again.

Good point. Another reason why this is not the better solution compared with fast/slow pointer.

• The solution with 2 pointers gives LTE error. But this solution is correct.

"""
struct ListNode *ptr1 = NULL;
struct ListNode *ptr2 = NULL;
bool hasCycle = false;
return false;
}

``````for (ptr1 = head; ; ptr1 = ptr1->next) {
if (ptr1 == NULL || ptr1->next == NULL || ptr1->next->next == NULL) {
hasCycle = false;
break;
}
ptr2 = ptr1->next->next;
if (ptr1 == ptr2) {
hasCycle = true;
break;
}
}

return hasCycle;
``````

}"""

• @selvamani.ramasamy
ptr1=ptr1->next;
ptr2=ptr1->next->next;
in each step, ptr2 only moves 2 more than ptr1,and ptr2 is always 2 step more than ptr1;
how can u make sure ptr1->next->next==ptr1?

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