The trick for solving RecursiveSum on HackerRank without running out of memory

Iterative Answer

def superD (somestring,k): 
summation = sum ( list ( map (int,somestring) ) )
print (somestring,summation*k)
return str ( sum ( list ( map (int,somestring) ) ) * k )
def superDigit (n, k):
x = superD (n , k )
#print (x)
for i in range (100):
x = superD (x , 1)
#print (x)
if len (x) == 1 :
print (x)
return x
else:
continue

Recursive Answer

Written by [1] in the Discussions

def superDigit(n, k):
def sum_digits(_int):
return int(sum(map(int, list(str(_int)))))
if len(str(n)) == 1:
return n
return superDigit(sum_digits(n)*k, 1)

Whether you solve it iteratively or recursively, there is one main trick; In the instructions, the string is repeated before the sum is computed. Thus, edge cases like the one below produced an out-of-memory error. While of course you never had to repeat the string before computing the summation. You can compute the summation once and multiply the summation itself by “k”.

somestring = "9875"
k = 8
print (sum (list (map (int , somestring*k))) == sum (list (map (int , somestring))) * k)
True

Edge Case causing Memory Error

7404954009694227446246375747227852213692570890717884174001587537145838723390362624487926131161112710589127423098959327020544003395792482625191721603328307774998124389641069884634086849138515079220750462317357487762780480576640689175346956135668451835480490089962406773267569650663927778867764315211280625033388271518264961090111547480467065229843613873499846390257375933040086863430523668050046930387013897062106309406874425001127890574986610018093859693455518413268914361859000614904461902442822577552997680098389183082654625098817411306985010658756762152160904278169491634807464356130877526392725432086439934006728914411061861235300979536190100734360684054557448454640750198466877185875290011114667186730452681943043971812380628117527172389889545776779555664826488520325234792648448625225364535053605515386730925070072896004645416713682004600636574389040662827182696337187610904694029221880801372864040345567230941110986028568372710970460116491983700312243090679537497139499778923997433720159174153 100000

[1] https://www.hackerrank.com/embrown801?hr_r=1

--

--

Emad Ezzeldin ,Sr. DataScientist@UnitedHealthGroup
Emad Ezzeldin ,Sr. DataScientist@UnitedHealthGroup

Written by Emad Ezzeldin ,Sr. DataScientist@UnitedHealthGroup

5 years Data Scientist and a MSc from George Mason University in Data Analytics. I enjoy experimenting with Data Science tools. emad.ezzeldin4@gmail.com

No responses yet