Coders Crushby Napplied AI
Back to DSA Problems
EasyMath & Geometry

Happy Number

Check if number is happy

Solution Approach

Detect cycle using set to track values. If sum reaches 1, number is happy. If cycle detected, number is unhappy.

Implementation
def isHappy(n):
    def sum_of_squares(num):
        total = 0
        while num:
            total += (num % 10) ** 2
            num //= 10
        return total
    
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n)
        n = sum_of_squares(n)
    return n == 1
Complexity Analysis

Time Complexity

O(log n)

Space Complexity

O(1)
Complexity
Time:O(log n)
Space:O(1)
Asked at
GoogleFacebook
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless