Skip to content

Commit d957287

Browse files
authored
Create 0202-happy-number.md
1 parent e2fc430 commit d957287

File tree

1 file changed

+337
-0
lines changed

1 file changed

+337
-0
lines changed
Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,337 @@
1+
---
2+
id: happy-number
3+
title: Happy Number
4+
sidebar_label: 202 Happy Number
5+
tags:
6+
- Hash Table
7+
- Two Pointers
8+
- C++
9+
- Python
10+
- Java
11+
description: "This document provides a solution for Happy Number problem on LeetCode."
12+
---
13+
14+
## Problem
15+
16+
Write an algorithm to determine if a number n is happy.
17+
18+
A happy number is a number defined by the following process:
19+
20+
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
21+
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
22+
- Those numbers for which this process ends in 1 are happy.
23+
24+
Return true if n is a happy number, and false if not.
25+
26+
### Examples
27+
28+
**Example 1:**
29+
30+
```
31+
Input: n = 19
32+
33+
Output: true
34+
35+
```
36+
**Example 2:**
37+
```
38+
Input: n = 2
39+
40+
Output: false
41+
42+
```
43+
44+
### Constraints
45+
46+
- `1 <= n <= 2^31 - 1`
47+
48+
---
49+
50+
### Intuition
51+
A happy number is defined as a number that, when repeatedly replaced by the sum of the squares of its digits, eventually reaches 1. If the process never reaches 1 and enters into a cycle, then the number is not a happy number.
52+
53+
## Approach
54+
55+
**1. Hash Map:**
56+
57+
This approach uses a hash map to keep track of numbers encountered during the process of computing the "next" number. If a number is encountered again, it indicates a cycle, and the function returns false. If the number 1 is encountered, the function returns true.
58+
59+
- Define a function next(num) to compute the next number based on the rules specified in the problem.
60+
61+
- Start with the given number n and repeatedly compute the next number until either 1 is encountered (indicating happiness) or a cycle is detected.
62+
63+
- Use a hash map to keep track of encountered numbers to detect cycles.
64+
65+
66+
#### Code in Java
67+
68+
```java
69+
import java.util.HashSet;
70+
import java.util.Scanner;
71+
72+
class Solution {
73+
private int next(int num) {
74+
int n = 0;
75+
while (num > 0) {
76+
int r = num % 10;
77+
n += (r * r);
78+
num /= 10;
79+
}
80+
return n;
81+
}
82+
83+
public boolean isHappy(int n) {
84+
HashSet<Integer> set = new HashSet<>();
85+
while (n != 1 && !set.contains(n)) {
86+
set.add(n);
87+
n = next(n);
88+
}
89+
return n == 1;
90+
}
91+
92+
public static void main(String[] args) {
93+
Solution solution = new Solution();
94+
Scanner scanner = new Scanner(System.in);
95+
System.out.print("Enter a number: ");
96+
int n = scanner.nextInt();
97+
if (solution.isHappy(n)) {
98+
System.out.println(n + " is a happy number.");
99+
} else {
100+
System.out.println(n + " is not a happy number.");
101+
}
102+
scanner.close();
103+
}
104+
}
105+
106+
```
107+
108+
#### Code in C++
109+
110+
```cpp
111+
#include <iostream>
112+
#include <unordered_map>
113+
114+
class Solution {
115+
private:
116+
int next(int num){
117+
int n = 0;
118+
while(num){
119+
int r = num % 10;
120+
n += (r * r);
121+
num /= 10;
122+
}
123+
return n;
124+
}
125+
public:
126+
bool isHappy(int n) {
127+
int num = n;
128+
std::unordered_map<int, int> mp;
129+
do {
130+
num = next(num);
131+
if(num == 1) return true;
132+
if(mp.find(num) != mp.end()) return false;
133+
else mp[num] = 1;
134+
} while(num != n);
135+
return false;
136+
}
137+
};
138+
139+
int main() {
140+
Solution solution;
141+
int n;
142+
std::cout << "Enter a number: ";
143+
std::cin >> n;
144+
if(solution.isHappy(n)) {
145+
std::cout << n << " is a happy number." << std::endl;
146+
} else {
147+
std::cout << n << " is not a happy number." << std::endl;
148+
}
149+
return 0;
150+
}
151+
152+
```
153+
154+
#### Code in Python
155+
156+
```py
157+
class Solution:
158+
def next(self, num):
159+
n = 0
160+
while num > 0:
161+
r = num % 10
162+
n += (r * r)
163+
num //= 10
164+
return n
165+
166+
def isHappy(self, n: int) -> bool:
167+
visited = set()
168+
while n != 1 and n not in visited:
169+
visited.add(n)
170+
n = self.next(n)
171+
return n == 1
172+
173+
if __name__ == "__main__":
174+
solution = Solution()
175+
n = int(input("Enter a number: "))
176+
if solution.isHappy(n):
177+
print(f"{n} is a happy number.")
178+
else:
179+
print(f"{n} is not a happy number.")
180+
181+
```
182+
183+
### Complexity Analysis
184+
185+
#### Time Complexity: $O(log n)$
186+
187+
> **Reason**: The primary operation is the sum of the squares of the digits of the number, which involves iterating over the digits. The number of digits in `n` is proportional to log base 10 of `n` i.e., $O(log n)$. Typically, the process of finding whether a number is happy converges quickly to either 1 (happy) or a cycle (not happy)..
188+
189+
#### Space Complexity: $O(log n)$
190+
191+
> **Reason**: The main space requirement is for storing previously seen numbers to detect cycles. The number of unique sums that can be encountered before either converging to 1 or entering a cycle is limited, and in practice, it's bound by a constant. However, in the worst case, the storage grows logarithmically with the size of `n`.
192+
193+
**2. Two Pointers:**
194+
195+
This approach uses Floyd's cycle detection algorithm, also known as the "tortoise and hare" algorithm. It employs two pointers, one slow and one fast, to detect cycles in the sequence of numbers.
196+
197+
- Define a function next(num) to compute the next number based on the rules specified in the problem.
198+
- Use two pointers, slow and fast, initialized to the given number n.
199+
- Advance slow by one step and fast by two steps at each iteration.
200+
- If a cycle is detected (i.e., slow equals fast), exit the loop.
201+
- If slow eventually reaches 1, return true; otherwise, return false.
202+
203+
204+
#### Code in Java
205+
206+
```java
207+
208+
import java.util.Scanner;
209+
210+
class Solution {
211+
private int next(int num) {
212+
int n = 0;
213+
while (num > 0) {
214+
int r = num % 10;
215+
n += (r * r);
216+
num /= 10;
217+
}
218+
return n;
219+
}
220+
221+
public boolean isHappy(int n) {
222+
int slow = n, fast = n;
223+
do {
224+
slow = next(slow);
225+
fast = next(next(fast));
226+
} while (slow != fast);
227+
return slow == 1;
228+
}
229+
230+
public static void main(String[] args) {
231+
Solution solution = new Solution();
232+
Scanner scanner = new Scanner(System.in);
233+
System.out.print("Enter a number: ");
234+
int n = scanner.nextInt();
235+
if (solution.isHappy(n)) {
236+
System.out.println(n + " is a happy number.");
237+
} else {
238+
System.out.println(n + " is not a happy number.");
239+
}
240+
scanner.close();
241+
}
242+
}
243+
244+
245+
```
246+
247+
#### Code in C++
248+
249+
```cpp
250+
#include <iostream>
251+
252+
class Solution {
253+
private:
254+
int next(int num) {
255+
int n = 0;
256+
while (num) {
257+
int r = num % 10;
258+
n += (r * r);
259+
num /= 10;
260+
}
261+
return n;
262+
}
263+
public:
264+
bool isHappy(int n) {
265+
int slow = n, fast = n;
266+
do {
267+
slow = next(slow);
268+
fast = next(next(fast));
269+
} while (slow != fast);
270+
return slow == 1;
271+
}
272+
};
273+
274+
int main() {
275+
Solution solution;
276+
int n;
277+
std::cout << "Enter a number: ";
278+
std::cin >> n;
279+
if (solution.isHappy(n)) {
280+
std::cout << n << " is a happy number." << std::endl;
281+
} else {
282+
std::cout << n << " is not a happy number." << std::endl;
283+
}
284+
return 0;
285+
}
286+
287+
```
288+
289+
#### Code in Python
290+
291+
```py
292+
class Solution:
293+
def next(self, num):
294+
n = 0
295+
while num > 0:
296+
r = num % 10
297+
n += (r * r)
298+
num //= 10
299+
return n
300+
301+
def isHappy(self, n: int) -> bool:
302+
slow = n
303+
fast = n
304+
while True:
305+
slow = self.next(slow)
306+
fast = self.next(self.next(fast))
307+
if slow == fast:
308+
break
309+
return slow == 1
310+
311+
if __name__ == "__main__":
312+
solution = Solution()
313+
n = int(input("Enter a number: "))
314+
if solution.isHappy(n):
315+
print(f"{n} is a happy number.")
316+
else:
317+
print(f"{n} is not a happy number.")
318+
319+
320+
```
321+
322+
### Complexity Analysis
323+
324+
#### Time Complexity: $O(log n)$
325+
326+
> **Reason**: The algorithm uses Floyd's cycle detection (tortoise and hare) which typically converges or detects a cycle quickly, resulting in O(log n) overall time complexity.
327+
328+
#### Space Complexity: $O(1)$
329+
330+
> **Reason**: The space complexity is constant, $O(1)$, since the algorithm only uses a few integer variables (slow, fast) for cycle detection and does not require any additional data structures like a hash set or hash map to store intermediate results.
331+
332+
333+
# References
334+
335+
- **LeetCode Problem:** [Number of Digit One](https://leetcode.com/problems/happy-number/description/)
336+
- **Solution Link:** [Number of Digit One Solution on LeetCode](https://leetcode.com/problems/happy-number/solutions/)
337+
- **Authors LeetCode Profile:** [Vivek Vardhan](https://leetcode.com/u/sidkul712/)

0 commit comments

Comments
 (0)