const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Happy Number LeetCode: Floyd's Cycle Detection Guide

Happy Number (#202) proves that Floyd's fast/slow pointer technique works on any sequence — not just linked lists. This walkthrough covers the hash set and cycle detection approaches with full complexity analysis.

8 min read|

Floyd's cycle detection works beyond linked lists

Detect cycles in any sequence with O(1) space — from linked lists to number theory

Happy Number LeetCode #202: Floyd's Cycle Detection for Number Sequences

Happy Number (#202) is one of those LeetCode problems that looks trivial at first glance — just sum the squares of digits and repeat. But the real insight is deeper. This problem proves that Floyd's cycle detection, the same fast/slow pointer technique you learned in Linked List Cycle (#141), works on any sequence that can loop.

Most candidates reach for a hash set and move on. That works, but interviewers are looking for candidates who recognize the deeper pattern: the digit-square-sum function generates a sequence, and that sequence either terminates at 1 or enters a cycle. This is structurally identical to detecting a cycle in a linked list.

In this walkthrough, you will see both the hash set approach and the Floyd's cycle detection approach, understand why Floyd's works here, and learn how to apply this pattern to other sequence-based problems.

Understanding the Happy Number Problem

Given a positive integer n, determine if it is a happy number. A happy number is defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat until the number either equals 1 (happy) or loops endlessly in a cycle (not happy).

For example, 19 is happy: 1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1. The sequence reaches 1, so 19 is a happy number.

The number 2 is not happy: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. The sequence enters a cycle at 4 and never reaches 1. The key insight is that the sequence must eventually either reach 1 or cycle — it cannot grow unbounded because the digit square sum of any number is always smaller than the number itself for sufficiently large inputs.

ℹ️

Interview Insight

Happy Number (#202) is a favorite Easy problem because it connects linked list cycle detection to number theory — interviewers love seeing you recognize Floyd's pattern outside of linked lists.

Approach 1: Hash Set for Happy Number Cycle Detection

The most intuitive approach is to track every number you have seen. Compute the digit square sum repeatedly and store each result in a hash set. If the result is 1, the number is happy. If you see a number that is already in the set, you have detected a cycle and the number is not happy.

This approach is straightforward to implement. Create a set, compute the digit square sum function, and loop until you either hit 1 or find a repeated value. The time complexity is O(log n) per step since the number of digits is proportional to log n, and the space complexity is O(log n) for the set of seen values.

The hash set approach is perfectly valid in interviews and often the first solution candidates write. However, it uses extra space proportional to the length of the cycle, which leads us to the optimized approach.

  • Create a hash set to store seen numbers
  • Compute digitSquareSum(n) by extracting each digit, squaring it, and summing
  • If the result is 1, return true — the number is happy
  • If the result is already in the set, return false — cycle detected
  • Otherwise, add the result to the set and repeat

Approach 2: Floyd's Fast/Slow Pointers for Happy Number

Floyd's cycle detection eliminates the hash set entirely. Instead of tracking seen values, use two pointers: slow computes one digit-square-sum step, and fast computes two steps. If the sequence cycles, the fast pointer will eventually meet the slow pointer. If the sequence reaches 1, the fast pointer hits 1 first.

Initialize slow = n and fast = digitSquareSum(n). In each iteration, advance slow by one step and fast by two steps. If fast equals 1, the number is happy. If slow equals fast, you have found a cycle. This runs in O(1) space because you only store two variables regardless of the sequence length.

The implementation is clean and mirrors Linked List Cycle (#141) almost exactly. Replace node.next with digitSquareSum and the logic is identical.

  • Set slow = n, fast = digitSquareSum(n)
  • Loop: slow = digitSquareSum(slow), fast = digitSquareSum(digitSquareSum(fast))
  • If fast === 1, return true
  • If slow === fast, return false (cycle found, not at 1)
  • Time: O(log n) per step, Space: O(1)
💡

Pro Tip

Floyd's works identically to Linked List Cycle: slow = digitSquareSum(slow), fast = digitSquareSum(digitSquareSum(fast)). If they meet at 1, happy. If they meet elsewhere, not happy.

Why Floyd's Cycle Detection Works for Happy Number

The digit-square-sum function maps every positive integer to another positive integer. This creates a sequence: n → f(n) → f(f(n)) → ... where f is the digit-square-sum function. Because the output is bounded (the digit square sum of a number with d digits is at most 81d, which eventually becomes smaller than the input), the sequence must eventually revisit a value.

This means the sequence either reaches 1 and stays there (since digitSquareSum(1) = 1) or enters a cycle that does not include 1. This is exactly the structure Floyd's algorithm was designed to detect — a sequence generated by repeatedly applying a function, where you need to determine if it reaches a fixed point or enters a cycle.

The beauty of this problem is that it demonstrates Floyd's algorithm is not a linked-list-specific trick. It works on any deterministic sequence. The digit square sum creates an implicit linked list where each number points to its successor. You do not need actual nodes or pointers — just a function that computes the next value.

Edge Cases for Happy Number

The simplest edge case is n = 1, which is trivially happy since digitSquareSum(1) = 1. The number 7 is also happy: 7 → 49 → 97 → 130 → 10 → 1. These are worth testing to verify your implementation handles the base case correctly.

For non-happy numbers, n = 2 demonstrates the cycle: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. The cycle length is 8, starting at 4. Any number that enters this cycle is not happy. In fact, every non-happy number eventually enters this exact same cycle.

Large numbers are not a concern for correctness because the digit square sum rapidly decreases for numbers above a few hundred. A 10-digit number has a maximum digit square sum of 810, so the sequence converges quickly. Both the hash set and Floyd's approach handle large inputs efficiently.

  • n = 1: trivially happy (digitSquareSum(1) = 1)
  • n = 7: happy (7 → 49 → 97 → 130 → 10 → 1)
  • n = 2: not happy, enters the 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 cycle
  • Large n: digit square sum converges quickly, no performance concern
⚠️

Common Mistake

The hash set approach is simpler to code but uses extra space — mention Floyd's as the O(1) space optimization even if you implement the hash set. Showing both approaches demonstrates depth.

What Happy Number Teaches About Cycle Detection

Happy Number (#202) is more than an easy problem to check off your list. It teaches a fundamental lesson: Floyd's cycle detection applies to any sequence generated by a deterministic function, not just linked lists. The same slow/fast pointer logic from Linked List Cycle (#141) works here without modification.

This pattern appears in other LeetCode problems too. Find the Duplicate Number (#287) uses Floyd's on array index mappings. Linked List Cycle II (#142) extends it to find the cycle start. Once you recognize that a problem involves detecting whether a sequence loops, Floyd's should be your first thought for an O(1) space solution.

Practice recognizing when a problem generates an implicit sequence. If you see repeated function application, bounded output, and a question about convergence or looping, Floyd's cycle detection is likely the optimal approach. Review this pattern alongside Linked List Cycle with YeetCode flashcards to build the intuition that makes these connections automatic.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now