the first code is written by me, but while executing it, I am getting Time Limit Exceeded.
class Solution:
def isHappy(self, n: int) -> bool:
l=set()
while(n not in l):
l.add(n)
x=0
while n:
s=str(n)
for i in s:
x+=(int(i)*int(i))
n=x
if(n==1):
return True
return False
And here is the second code, while executing, this runs perfectly fine.
class Solution:
def isHappy(self, n: int) -> bool:
visit = set()
while n not in visit:
visit.add(n)
n = sumofSquares(n)
if n == 1:
return True
return False
def sumofSquares(n):
output = 0
while n:
for i in str(n):
output += int(i) * int(i)
return output
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:
def isHappy(n: int) -> bool:
visit = set()
while n not in visit:
visit.add(n)
square_sum = 0
for i in str(n):
square_sum += int(i)**2
n = square_sum
if n == 1:
return True
return False
for i in range(20):
print(i, isHappy(i))
# prints 'True' for:
# 1, 7, 10, 13, 19