Example 1
- Input
- n = 19
- Output
- true
The successors are , , , and . Reaching 1 makes the answer true.
Repeatedly replace n with the sum of the squares of its digits, returning true if the chain reaches 1 and false if it falls into a repeating cycle.
Decide whether a positive integer n is a happy number. Repeatedly replace the number by the sum of the squares of its decimal digits.
Return true if the sequence reaches 1. Return false if it repeats indefinitely without reaching 1. Since the successor of 1 is again 1, reaching that value is enough to finish.
The successors are , , , and . Reaching 1 makes the answer true.
The initial value already equals 1; no transformation is needed. Its successor is also 1.
The chain visits 2, 4, 16, 37, 58, 89, 145, 42, 20, then 4 again. A repeated 4 repeats the same successors forever without reaching 1.
The digit-square rule gives each number exactly one successor. For Example 1, the chain is 19 to 82 to 68 to 100 to 1. A repeated value would force every later successor to repeat too, so the real task is detecting a cycle. Since a permitted input has at most ten digits, its first successor is at most 810; every later successor is at most 243. This finite range guarantees eventual repetition, including the happy fixed point 1.
Reveal Hash Set Cycle: intuition, complexity, and code
19 goes (19 to 82 to 68 to 100 to 1) and where 2 goes. What separates the two chains?1 or repeats a value forever.1.n = 1 is already happy: both loops exit at once and return true.n = 7 is happy through a longer chain (7 to 49 to 97 to 130 to 10 to 1), so chains are not always short.n = 2 never reach 1, so without cycle detection the loop runs forever.n becomes 1 with no record of seen values, which hangs forever on unhappy inputs such as 2./ 10 in JavaScript, which keeps fractions; apply Math.floor after each division.Any process mapping each value to a next value inside a bounded range must eventually repeat, so cycle tools such as seen sets and fast/slow pointers apply far beyond linked lists.