Replace a number by the sum of the squares of its digits, again and again. It is happy if this reaches 1, otherwise it loops forever.
DSA Animator › DSA Revision › Linked List › Happy Number
Remember: any repeated next function forms a linked list. Floyd detects the loop without a set. The video solves Happy Number (LeetCode 202, Easy) with the Cycle Detection pattern from the Linked List topic, and you can replay every step in the interactive Happy Number animation.
Replace a number by the sum of the squares of its digits, again and again. It is happy if this reaches 1, otherwise it loops forever.
19 goes to 82, then 68, then 100, then 1, so 19 is happy. 2 is not happy, because it falls into a loop through 4, 16, 37 and back to 4.
You can store every number you see in a set and stop on a repeat. That uses extra memory.
The sequence behaves like a linked list, where next is the digit square sum. So use fast and slow pointers, exactly as in cycle detection. If fast reaches 1, the number is happy, and if they meet elsewhere, it is not.
Slow goes to 82 and fast to 68. Slow goes to 68, and fast jumps through 100 to 1. Fast has reached 1. So 19 is happy.
In code, a helper computes the digit square sum. Move slow once and fast twice until fast is 1 or they meet. Return whether fast is 1, so it's O of log n per step and O of 1 space.
Remember: any repeated next function forms a linked list. Floyd detects the loop without a set.