educative.io

I do not understand the logic. When do we stop? How dow we know it's gonna be an infinite loop?

I do not understand the logic. When do we stop? How dow we know it’s gonna be an infinite loop?

We use Fast and Slow pointers to detect the cycle (infinite loop). The algorithm is based on the Floyd’s cycle-finding algorithm (also called the “tortoise and the hare algorithm”). If the Fast pointer reaches 1, we come to know that the number is a Happy number. Otherwise, the Fast pointer would reach the Slow pointer which depicts that a cycle is detected and the number is not a Happy number.

1 Like