The problem uses a LinkedList, as part of the lesson. Given that we don’t have the restriction to use a specific data structure, isn’t it more efficient to solve this problem using a dictionary/hashmap.
the code would look like this:
def find_happy_number(num):
dict = {}
while num != 1:
# split the num by digits
num_list = [int(i)**2 for i in str(num)]
num = sum(num_list)
dict[num] = dict.get(num, 0) + 1
if dict[num] > 1:
# found a cycle
return False
return True
we don’t have any recursive calls, neither have to continue calculating the squares once we detect a duplicate number.
Share your thoughts please.