AlgoInsight

DSA problem

Happy Number

EasyFast and Slow PointersPattern: Fast and Slow Pointerstop300AmazonMicrosoftGoogleAppleAirbnb

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. Repeat until the number equals 1 (the number is happy) or until it loops endlessly in a cycle that never reaches 1 (the number is not happy). Return true if n is a happy number and false otherwise.

At first glance this looks like a number-theory problem, but it is secretly a cycle-detection problem on an implicit "linked list". Each integer x has a single successor: the sum of the squares of its digits. Following successors traces out a sequence n → f(n) → f(f(n)) → ... that behaves exactly like walking pointers in a linked list. Either the sequence reaches 1 and stays there (happy), or it enters a cycle that does not contain 1 (unhappy).

A common but space-heavy solution stores every number seen in a hash set and returns false the moment a repeat appears. That works, but it can grow without a tight bound and adds overhead.

The optimal approach uses Floyd's tortoise-and-hare cycle detection directly on this sequence. The slow pointer advances by one squared-digit-sum per iteration; the fast pointer advances by two. If the sequence reaches 1, the fast pointer hits 1 first and we return true. Otherwise, because the sequence must eventually cycle (the values are bounded, so the pigeon-hole principle guarantees a repeat), slow and fast will meet at some value other than 1 — and that meeting tells us n is not happy. The algorithm uses only two integer variables, so it runs in O(log n) time and O(1) space.

Examples

Example 1
Input: n = 19
Output: true
Explanation: 1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1. The sequence reaches 1, so 19 is happy.
Example 2
Input: n = 2
Output: false
Explanation: The sequence is 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 ... and cycles back to 4 without ever reaching 1. So 2 is not happy.
Example 3
Input: n = 1
Output: true
Explanation: The number 1 is already the fixed point of the process, so it is trivially happy.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

mathtwo-pointersfast-slow-pointershash-table

Browse all DSA problems