We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I've just spent half an hour looking through this and the parent comments above (which are given some credit for the idea) - it's a really clever solution to the problem, and if you read petreeftime's description above, it covers it pretty well. I found a key to understanding it was to alter the code so that you see the contents of all the relevant variables at each step, and then it became clear how it was working (I'm using Python 3.6, hence the f strings):
defdivisibleSumPairs(n,k,ar):nums=[0]*kcount=0foreleinar:modu=ele%kprint(f"{ele}{modu}{count}{nums} - after modu")count+=nums[(k-modu)%k]print(f"{ele}{modu}{count}{nums} - after count+=")nums[modu]+=1print(f"{ele}{modu}{count}{nums} - after nums+=")print("-----------------------")returncount
The first step works out the mod value of the current array element - that's really the only thing that matters - a 3 and a 6 will have the same effect as a 3 and a 3 (for a k of 3).
Next step is to increment the counter by the number of possible combinations that yield k mod 0.
The third step adds the current array element to the nums list, which will allow that to be counted towards future possibilities in other steps.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Divisible Sum Pairs
You are viewing a single comment's thread. Return to all comments →
I've just spent half an hour looking through this and the parent comments above (which are given some credit for the idea) - it's a really clever solution to the problem, and if you read petreeftime's description above, it covers it pretty well. I found a key to understanding it was to alter the code so that you see the contents of all the relevant variables at each step, and then it became clear how it was working (I'm using Python 3.6, hence the f strings):
The first step works out the mod value of the current array element - that's really the only thing that matters - a 3 and a 6 will have the same effect as a 3 and a 3 (for a k of 3).
Next step is to increment the counter by the number of possible combinations that yield k mod 0.
The third step adds the current array element to the nums list, which will allow that to be counted towards future possibilities in other steps.