Happy Number
LeetCode 202 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Floyd's cycle detection on the digit-square sequence.
நான் Happy Number (LeetCode 202) ஐ இப்படித் தீர்த்தேன் — Two Pointers பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Repeatedly replacing a number by the sum of the squares of its digits either reaches 1 or falls into a cycle. Detecting the cycle is the same problem as a linked-list loop: run a slow and a fast pointer over the sequence.
Approach
- 1
get_next(n) sums the squares of the digits.
- 2
slow moves one step, fast moves two.
- 3
Stop when fast hits 1 (happy) or meets slow (cycle).
- 4
First version: recursion with a hard-coded shortcut for small non-happy numbers.
நான் எப்படித் தீர்த்தேன் · முதல் யோசனையிலிருந்து இறுதித் தீர்வு வரை
Recurse on the digit-square sum.
Two pointers over the sequence.
Recursion with shortcutPythonO(log n) per step
class Solution:
def isHappy(self, n: int) -> bool:
total = 0
if n==1:
return True
if n>1 and n<7:
return False
while n>0:
num = n%10
total+=num**2
n=n//10
return self.isHappy(total)Floyd slow / fastPythonO(log n) · O(1) space
class Solution:
def isHappy(self, n: int) -> bool:
def get_next(n):
total = 0
while n>0:
num = n%10
total+=num**2
n=n//10
return total
slow = n
fast = get_next(n)
while fast!=1 and slow!=fast:
slow = get_next(slow)
fast = get_next(get_next(fast))
return True if fast==1 else FalseHappy Number — அடிக்கடி கேட்கப்படும் கேள்விகள்
Happy Number பின்னாலுள்ள intuition என்ன?
Repeatedly replacing a number by the sum of the squares of its digits either reaches 1 or falls into a cycle. Detecting the cycle is the same problem as a linked-list loop: run a slow and a fast pointer over the sequence.
Happy Number (LeetCode 202) ஐ எப்படித் தீர்ப்பது?
1. get_next(n) sums the squares of the digits. 2. slow moves one step, fast moves two. 3. Stop when fast hits 1 (happy) or meets slow (cycle). 4. First version: recursion with a hard-coded shortcut for small non-happy numbers.
Happy Number இன் time மற்றும் space complexity என்ன?
Time: O(log n) per step. Space: O(1). (Accepted approach: Floyd slow / fast.)
Happy Number இல் பொதுவான தவறுகள் என்ன?
A set of seen values also works, at O(k) memory.
Happy Number ஐத் தீர்க்க ஒன்றுக்கு மேற்பட்ட வழிகள் உள்ளனவா?
Recursion with shortcut (O(log n) per step): Recurse on the digit-square sum. Floyd slow / fast (O(log n) · O(1) space): Two pointers over the sequence.