↓Skip to main content
  1. LeetCode/

LeetCode 202: Happy Number

·1 min· ·
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-21

  • Submissions: Runtime Error → Wrong Answer → Runtime Error → Wrong Answer → Accepted → Wrong Answer → Accepted

Approach
#

Repeatedly summing squared digits shrinks the number quickly, ending either at 1 or in a cycle without 1. A set of seen numbers detects the cycle on a repeat (or use fast and slow pointers from Linked List Template 3 for O(1) space).

My Attempts
#

Both WAs had the same bug: the loop kept computing the sum from the original n without updating it, so the second round repeated: 94 reaches 1, but it returned False.

Solution
#

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            n = sum(int(c) ** 2 for c in str(n))
        return n == 1

Complexity
#

Each step is O(log n) and there are few steps; space O(steps).

Mistakes to Avoid
#

  • Each round must use the new number; update n.

Interview Explanation
#

I keep replacing the number with its squared-digit sum, tracking seen numbers in a set; reaching 1 means happy, a repeat means a cycle without 1. Effectively O(log n).

Related

LeetCode 141: Linked List Cycle
·2 mins
LeetCode Easy Hash-Table Linked-List Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 141 note: Floyd’s cycle detection, fast two steps and slow one; with a cycle they must meet, each advancing from its own position
LeetCode 160: Intersection of Two Linked Lists
·2 mins
LeetCode Easy Hash-Table Linked-List Two-Pointers
LeetCode 160 note: each pointer walks its own list then the other’s; both cover lenA + lenB steps and reach the intersection, or None, together
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)
LeetCode 205: Isomorphic Strings
·2 mins
LeetCode Easy Hash-Table String
LeetCode 205 note: characters must map one to one; it holds when the distinct characters and distinct pairs all have the same count
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate