Hello. Since I couldn’t find any proper answer to this question, I searched on the web.
Here is what i could find as a satisfactory explanation from leetcode discussion on this problem -
The time complexity of this implementation is O(klog(n))
n is the input number
k is the number of iterations required to determine whether the number is happy.
Each iteration of the while loop involves calculating the sum of the squares of the digits in n, which takes log(n) time (since there are log(n) digits in the number n, and each digit requires a constant amount of time to square and sum). Therefore, the time complexity of each iteration of the while loop is O(log(n))
Overall, the while loop runs at most k times, so the total time complexity of the algorithm is O(klog(n))
The space complexity of this implementation is also O(k), since the set of visited numbers can contain at most k numbers. Note that the maximum value of k is unbounded, so the space complexity could potentially be very large for very large input numbers.
In practice, however, the value of k is typically quite small for most input numbers, so the actual time and space complexity of this implementation is usually much lower than the worst-case complexity.