the first code is written by me, but while executing it, I am getting Time Limit Exceeded.
JavaScript
x
15
15
1
class Solution:
2
def isHappy(self, n: int) -> bool:
3
l=set()
4
while(n not in l):
5
l.add(n)
6
x=0
7
while n:
8
s=str(n)
9
for i in s:
10
x+=(int(i)*int(i))
11
n=x
12
if(n==1):
13
return True
14
return False
15
And here is the second code, while executing, this runs perfectly fine.
JavaScript
1
17
17
1
class Solution:
2
def isHappy(self, n: int) -> bool:
3
visit = set()
4
while n not in visit:
5
visit.add(n)
6
n = sumofSquares(n)
7
if n == 1:
8
return True
9
return False
10
11
def sumofSquares(n):
12
output = 0
13
while n:
14
for i in str(n):
15
output += int(i) * int(i)
16
return output
17
So guys can you all tell me the difference between the time complexity of these two codes and also why is this happening?
Advertisement
Answer
The code you’re writing does an infinite loop, try running (by hand) your code and the second code with n=1
Here is a working code:
JavaScript
1
17
17
1
def isHappy(n: int) -> bool:
2
visit = set()
3
while n not in visit:
4
visit.add(n)
5
square_sum = 0
6
for i in str(n):
7
square_sum += int(i)**2
8
n = square_sum
9
if n == 1:
10
return True
11
return False
12
13
for i in range(20):
14
print(i, isHappy(i))
15
# prints 'True' for:
16
# 1, 7, 10, 13, 19
17