Skip to content
Discussion options

You must be logged in to vote

This should answer your problem:

from collections import defaultdict

def subarrays_div_by_k(nums, k):
count_by_rem = defaultdict(int)
count_by_rem[0] = 1

total = 0
pref = 0
for x in nums:
    pref += x
    rem = (pref % k + k) % k  # normalize for negatives
    total += count_by_rem[rem]
    count_by_rem[rem] += 1

return total

test this with:

print(subarrays_div_by_k([4, 5, 0, -2, -3, 1], 5)) # 7

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by HarnoorMalik
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question Ask and answer questions about GitHub features and usage Programming Help Discussions around programming languages, open source and software development
4 participants