How to Solve - Happy Number - Leet Code Problem in Java ? - LeetCode | Happy Number | Java | Solution.java
ProblemÂ
https://leetcode.com/problems/happy-number/
Initial Solution (Recursion)
First I tried using recursion, it worked for the test case provided but when I executed it against some custom test cases with Input: n=11, 12, 13 etc.
To detect that the loop will run endlessly we need to check if the value generated has appeared earlier. We can use a HashSet for the same as it can search its element in O(1) and we don’t need to store duplicate values.
the execution was either getting into StackOverflow exception or was very slow. So it was unable to return any result due to the timeout or exceeding the stack size.
Recommended Solution (Optimal — Non Recursion)
Then I decided to implement it using iterative / non recursive approach.
Below is my solution which has passed many test cases and is accepted by LeetCode as correct solution.
















