← Whiteboard questions

Happy Number

Find out whether repeated digit squares reach 1

DSA, Easy, Math & Geometry

Which structure or algorithm, and what does it cost.

Pick a positive whole number n. One round replaces it with the total of its digits, each squared. One round turns 13 into 1 + 9 = 10. Keep playing rounds on each new result. A start is happy if some round gives exactly 1. Every other start cycles for ever. Write is_happy(n) to say whether n is happy, as True or False.

Examples

Input n = 23
Output True
Why 23 gives 4 + 9 = 13, then 1 + 9 = 10, then 1 + 0 = 1.
Input n = 116
Output False
Why 116 gives 38, 73, 58, 89, 145, 42, 20, 4, 16, 37, and then 58 again. The game loops without reaching 1.
Input n = 1
Output True
Why the start is already 1.

Constraints

Your answer must contain

Target Aim for O(log n) time and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Play the game by hand on a small start. Watch the numbers it makes, and see what happens when it does not reach 1.

Hint 2 the approach

A start that never reaches 1 must meet some number twice. Ask how you can tell that a number has come back.

Hint 3 the key step

Send two runners down the chain, one moving a step and one moving two. If the fast one reaches 1, the start is happy. If they meet first, it loops.

Walkthrough

Full walkthrough brute force to best

Brute force

Play the game and stop after a fixed number of rounds, for example 20. Say happy if 1 appeared. This works here, but only because every start up to 999 was checked and every start up to 1,000,000,000,000 lands on one of those after one round, and happy ones need at most 7 rounds. The cap is a fact the reader must trust. Each round costs one pass over the digits.

Better method

Keep a set of the numbers already seen. Stop when the number is 1 (happy) or already in the set (a loop, so not happy). No cap is needed. The set holds fewer than 1,000 numbers here, but its size depends on how long the chain runs.

Best method

Use two runners on the chain, with no set. The slow one moves one step per round and the fast one moves two. After the first round every number is at most 972, so the chain stays in a small range and must either reach 1, which then stays 1, or enter a loop. If a loop exists, the fast runner closes in on the slow one inside it and they meet. If the chain reaches 1, the fast runner gets there first. So stop when the fast runner shows 1 (happy) or the runners meet before that (a loop, not happy). Only two numbers are kept.

Hand trace

Run on n = 23. Start with slow 23 and fast 13, which is one step ahead. Neither is 1 and they differ, so play a round. Slow moves one step to 13. Fast moves two steps: 13 to 10, and 10 to 1. Now fast is 1, so stop. The result is True.

Code

def digit_square_sum(n):
    total = 0
    while n:
        n, d = divmod(n, 10)
        total += d * d
    return total
def is_happy(n):
    slow, fast = n, digit_square_sum(n)
    while fast != 1 and slow != fast:
        slow = digit_square_sum(slow)
        fast = digit_square_sum(digit_square_sum(fast))
    return fast == 1

Time and memory

O(log n) time: the first step reads the digits of n, and every later number is at most 972, so the rounds cost a fixed amount. O(1) memory: two numbers.

Common mistakes

  • Playing until the number is 1 with no loop check. An unhappy start never ends.
  • Starting both runners at n. The test that they differ fails at once, and the loop does not run.
  • Adding the digits instead of adding their squares.

Related problems

More Math & Geometry problems
Happy Number: hints, walkthrough and Python solution