Determine Convergence of Digit-Square Sums
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Simulate a transformation that replaces a number with the sum of its squared digits, determining if it terminates at 1 or loops indefinitely.
Given a positive integer n, apply a sequence of transformations where each step replaces the current integer with the sum of the squares of its base-10 digits.
Determine whether this process eventually reduces the number to 1.
Specifically:
- If the sequence reaches
1, it will remain1permanently (1maps to1), so returnTrue. - If the sequence enters a cycle that does not include
1, it will repeat infinitely, so returnFalse.
Constraints
1 <= n <= 2^31 - 1
Examples
Example 1
Input: is_happy(7)
Output: True
Example 2
Input: is_happy(2)
Output: False
Example 3
Input: is_happy(1)
Output: True
Hints
Hint 1
Think of the sequence of transformed values as nodes in a directed graph where every node has out-degree 1.
Hint 2
Upper bounds: calculate the maximum possible value after a single transformation step for a 10-digit number. Notice how quickly numbers shrink.
Hint 3
To detect whether a sequence enters an infinite loop, record previously visited numbers in a hash set or use Floyd's tortoise-and-hare cycle-finding algorithm.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can model the process as traversing a directed state graph where every number $k$ transitions deterministically to a single successor: the sum of the squares of its decimal digits.
Because every state has a unique outgoing edge, starting from $n$ leads to one of two outcomes:
- The path hits
1. Since $1^2 = 1$,1transitions to1indefinitely. - The path loops back to a previously visited value other than
1, entering a repeating cycle.
To detect which condition occurs, we can maintain a hash set of observed numbers during the simulation. At each step, if the current value is already in the set, we have found a cycle and should return False. If the value becomes 1, we return True.
Mathematical Proof of Termination
Why is the set guaranteed to remain small, and why does the loop always end?
- For a number with $d$ digits, the maximum digit-square sum is $81 \cdot d$.
- For $d \ge 4$, $81 \cdot d < 10^{d-1} \le n$, meaning numbers with 4 or more digits always decrease after one step.
- The largest input $2^{31} - 1 = 2,147,483,647$ has 10 digits, giving a maximum first-step sum of $10 \cdot 81 = 810$.
- Any number $\le 999$ yields at most $3 \cdot 81 = 243$.
Hence, after at most one step, the number drops below $810$, and subsequent steps stay strictly within the small range $[1, 243]$. Since there are finitely many values, the trajectory must either reach 1 or repeat a value within very few iterations.
Complexity
- Time Complexity: $O(\log n)$. Extracting and squaring digits of a number $x$ takes $O(\log x)$ time. Since $n$ immediately drops into a small bounded range ($\le 810$), the total number of steps is $O(1)$. Thus, the time complexity is dominated by the initial step, which takes $O(\log n)$ time.
- Space Complexity: $O(1)$ auxiliary space. The set stores at most a few hundred small integers.
Extended Note: $O(1)$ Space Alternative
If memory must be minimized further without using a hash set, Floyd's Cycle-Finding Algorithm ("tortoise and hare") can be used:
- Advance a
slowpointer by $1$ step and afastpointer by $2$ steps. - If
fastreaches $1$, returnTrue. - If
slow == fast, a cycle is detected; returnFalse.
Implementation
def is_happy(n: int) -> bool:
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return n == 1