Detecting Happy Numbers with Slow & Fast Pointers

Day 14 of DSA 🎯 How Slow & Fast Pointers Can Be Used in Numbers We usually think of slow & fast pointers in linked lists. But did you know we can use the same concept in numbers too? 🤯 📍 Problem: Happy Number (LeetCode 202) A number is happy if we replace it by the sum of the squares of its digits repeatedly, and eventually reach 1. If it loops endlessly in a cycle that doesn’t include 1, it’s not happy. ✅ Key Idea Treat the process as a sequence. If we end up in a cycle (not reaching 1), slow & fast pointers will eventually meet. 📌 Example n = 19 19 → 82 → 68 → 100 → 1 ( Reaches 1 → Happy Number ✅ ) n = 2 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 (Cycle) ( Never reaches 1 → Not Happy ❌ ) Python Code class Solution: def fun(self, n: int) -> int: sum_n = 0 while n > 0: d = n % 10 total += d * d n //= 10 return sum_n def isHappy(self, n: int) -> bool: slow, fast = n, n while fast != 1: slow = self.fun(slow) fast = self.fun(self.fun(fast)) if slow == fast: # cycle detected return False return True 🚀 Why Does It Work? The sequence of sums is always within a limited range. So either it reaches 1 (happy) or enters a cycle (not happy). Slow pointer moves 1 step, fast pointer moves 2 steps. If there’s a cycle, they must meet. 💡 Key Takeaway Slow & fast pointers are not just for linked lists. They are powerful for detecting cycles in sequences, arrays, and even numbers! That’s it for Day 14! 🚀 Every problem solved today is a step closer to becoming the best version of me. #DSA #100DaysOfCode #LeetCode #HappyNumber #TwoPointers #LearningInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories