Magicsheet logo

Happy Number

Easy
99%
Updated 6/1/2025

Happy Number

What is this problem about?

The Happy Number coding problem asks you to determine if a given positive integer nn is "happy." A happy number is defined by a process where you replace the number with the sum of the squares of its digits. You repeat this process until the number either equals 1 (at which point it stays 1) or it enters a cycle that does not include 1. If the process ends in 1, the number is happy; otherwise, it is unhappy.

Why is this asked in interviews?

This question is a staple in interviews at companies like Amazon, Google, and Microsoft because it tests two fundamental skills: mathematical logic and cycle detection. While the problem sounds like a simple math exercise, the real challenge lies in identifying when a number has entered an infinite loop. It evaluates whether a candidate can recognize patterns in data sequences and choose the appropriate data structure to track history.

Algorithmic pattern used

There are two primary ways to solve the Happy Number interview question. The first is using a Hash Table interview pattern (specifically a Hash Set) to store every number generated in the sequence. If a number repeats, a cycle is detected. The second, more memory-efficient approach is Floyd's Cycle-Finding Algorithm (also known as the "Tortoise and the Hare"). By using two pointers moving at different speeds through the sequence of sums, you can detect a loop without storing the entire history.

Example explanation

Let's trace the number 19:

  1. Calculate 12+92=1+81=821^2 + 9^2 = 1 + 81 = 82.
  2. Calculate 82+22=64+4=688^2 + 2^2 = 64 + 4 = 68.
  3. Calculate 62+82=36+64=1006^2 + 8^2 = 36 + 64 = 100.
  4. Calculate 12+02+02=11^2 + 0^2 + 0^2 = 1. Since we reached 1, 19 is a Happy Number.

In contrast, if we took a number like 2, the sequence would eventually repeat a previously seen number (like 4, 16, 37, 58, 89, 145, 42, 20, 4...), indicating it is caught in a cycle and is not happy.

Common mistakes candidates make

  • Infinite Loops: Failing to implement a mechanism to detect cycles, causing the program to run forever on unhappy numbers.
  • Inefficient Digit Extraction: Converting the number to a string to get digits instead of using the more efficient modulo (% 10) and division (/ 10) operators.
  • Memory Overhead: Using a list instead of a set for history, resulting in O(N)O(N) lookup times instead of O(1)O(1).

Interview preparation tip

When you encounter a problem that involves a sequence of transformations, always ask yourself: "Can this sequence loop?" If yes, cycle detection patterns like Hash Sets or Two Pointers are your go-to tools. Practice the "Tortoise and the Hare" logic as it demonstrates a deeper understanding of space complexity optimization (O(1)O(1) space).

Similar Questions