Happy Number
Problem Statement
Start with a positive integer n. Replace it with the sum of the squares of its digits, and keep doing that.
If this process ever reaches 1, the number is happy. If it never reaches 1 (it keeps going round the same numbers forever), it is not happy.
Return true if n is happy, otherwise false.
A positive integer n.
true if repeating "sum of squared digits" reaches 1, otherwise false.
1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1. We reached 1.
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → … The numbers repeat from 4 and never reach 1.
- • 1 ≤ n ≤ 2^31 − 1
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Store every number produced; a repeat before 1 means not happy
slow = next(slow), fast = next(next(fast)); stop at 1 or when they meet
Keep producing the next number. Put each one into a hash set. If we reach 1, return true. If we produce a number that is already in the set, the sequence will repeat the same numbers forever without reaching 1, so return false.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Linked List — Fast & Slow translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.