Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Nabeel Keblawi
Alternative solution without using two pointers

Nabeel Keblawi

Oct 6, 2024

I wasn't sure how to use two pointers to solve this problem. So I took a different approach. I created a list to store all the sums calculated until a repeating sum was found, in which case is the beginning of a repetitive cycle.

Here's what I did:

class Solution: def find(self, num): # Initialize the current sums variable and an empty list to keep track of all sums ssum = num list_ssums = [] # Repeat this block as long as the sum isn't being repeated (not found in list_ssums) while ssum not in list_ssums: list_ssums.append(ssum) digits = self.num_split(ssum) ssum = self.calc_squares(digits) if ssum == 1: return True # Base case: return True if 1 is found return False # If any sum repeats itself, break and return False # Function that splits the digits def num_split(self, num): digits = [int(digit) for digit in str(num)] return digits # Function that calculates the sum of squares def calc_squares(self, digits): sums = 0 for digit in digits: sums += digit ** 2 return sums

0

0

Comments
Comments
Nabeel Keblawi
Nabeel Keblawia year ago

However it may not be the most efficient solution as time complexity is O((logN)^2) and space is O(logN).

On this page