Same code but one with time limit exceeded as output and another works perfectly fine

Question:

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?

Asked By: Sneh Agrawal

||

Answers:

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
Answered By: Be Chiller Too

The infinite loop happens in this block:

    while n:
        s=str(n)
        for i in s:
            x+=(int(i)*int(i))
        n=x

Whereas, the equivalent code also has an infinite loop, but able to exit because return exits the function (hence exit the while-loop as well):

    while n:
        for i in str(n):
            output += int(i)*int(i)
        return output
Answered By: perpetualstudent
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.