LeetCode 202: Happy Number — Step-by-Step Visual Trace
Easy — Two Pointers | Math | Hash Table | Floyd’s Algorithm
The Problem
Determine if a number is happy by repeatedly replacing it with the sum of the square of its digits until it equals 1 (happy) or loops endlessly in a cycle (not happy).
Approach
Uses Floyd’s cycle detection algorithm (tortoise and hare) with two pointers moving at different speeds to detect if the sequence enters a cycle or reaches 1. The helper function calculates the sum of squares of digits efficiently using divmod.
Time: O(log n) · Space: O(1)
Code
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(num):
next_num = 0
while num > 0:
num, digit = divmod(num, 10)
next_num += digit**2
return next_num
slow, fast = n, get_next(n)
while fast != 1 and slow != fast:
slow = get_next(slow)
fast = get_next(get_next(fast))
return fast == 1
Watch It Run
Try it yourself: Open TraceLit and step through every line.
Built with TraceLit — the visual algorithm tracer for LeetCode practice.
Comments