I’m stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.
Background
The question:
For an input of string n and integer k, the number h is created by concatenating n “k” times. Find the “super digit” of h by recursively summing the integers until one is left.
For example:
- n = ‘9875’, k = 2, so h = 98759875
- sum(98759875)= 58
- sum(58)= 13
- sum(13) = 4
Submissions
My Solution
def superDigit(n, k): h=n*k while len(h)>1: h=str(sum([int(i) for i in h])) return int(h)
Solution I’ve Found
def superDigit(n, k): return 1 + (k * sum(int(x) for x in n) - 1) % 9
My Inquiry to the Community
What am I missing in my solution? Yes it’s not as simple as the supplied solution involving the digital root function (which I don’t fully understand, I just found it online) but I don’t see how my function is supplying incorrect answers. It passes most of the test cases but is rejecting for 1/3 of them.
Advertisement
Answer
Thanks to some helpful comments from @Tim Roberts, @Paul Hankin, and @yagod I was able to solve the issue. It was in fact due to time-out! All I had to do was update one line: h=str(sum([int(i) for i in n])*(k%9))