DSA AnimatorDSA animations
Happy Number LC #202 Easy Floyd's Cycle Detection
Problem

Write an algorithm to determine if a number n is happy. A happy number is defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle that does not include 1. Return true if n is a happy number, and false if not.

Example 1
Input: n = 19
Output: true
Explanation: 1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1
Example 2
Input: n = 2
Output: false
Explanation: Sequence enters a cycle: 2→4→16→37→58→89→145→42→20→4→… (cycle!)
Constraints: 1 ≤ n ≤ 2³¹ − 1
Try Examples
Custom:
Digit-Square Sequence Chain
Digit-Square Breakdown
slow = — →
—
fast = — → getNext(getNext(fast))
—
State Variables
🐢 slow
—
🐇 fast
—
Iterations
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init slow = n, fast = getNext(n)
2
Loop while fast ≠ 1 and slow ≠ fast
3
Advance: slow = getNext(slow), fast = getNext(getNext(fast))
4
If fast == 1 → return true (happy!)
5
If slow == fast ≠ 1 → return false (cycle!)
Time
O(log n)
Space
O(1)
Why Floyd's Cycle Detection?

Every number maps deterministically to one successor via getNext. This creates an implicit linked list. For non-happy numbers, the sequence eventually revisits a value, forming a cycle. Floyd's algorithm detects any cycle in O(1) space — the fast pointer laps the slow pointer inside the cycle. For happy numbers, fast reaches 1 before any meeting occurs (since getNext(1) = 1, it loops at 1 forever).

How to solve Happy Number

LeetCode 202 · Easy · Linked List · Pattern: Cycle Detection

Why the obvious approach is slow

You can store every number you see in a set and stop on a repeat. That uses extra memory.

The key idea

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.

Remember

Any repeated next function forms a linked list. Floyd detects the loop without a set.

Run the animation above on your own input, or watch the 1:12 video explanation of Happy Number with a dry run and Java code.

More Linked List problems