Leetcode Problem #176681
-
Discussion TypeProduct Feedback Discussion ContentI'm stuck with the following problem: Count subarrays with sum divisible by k. Given an integer array nums and an integer k (k ≠ 0), return the number of non-empty contiguous subarrays whose sum is divisible by k. Example nums = [4, 5, 0, -2, -3, 1], k = 5 → 7 Constraints 1 ≤ len(nums) ≤ 2e5 -1e9 ≤ nums[i] ≤ 1e9 -1e9 ≤ k ≤ 1e9, k ≠ 0 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
This should answer your problem: from collections import defaultdict def subarrays_div_by_k(nums, k): test this with:print(subarrays_div_by_k([4, 5, 0, -2, -3, 1], 5)) # 7 |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for posting in the GitHub Community, @HarnoorMalik! We're happy you're here. You are more likely to get a useful response if you are posting your question in the applicable category, the Discussions category is solely related to conversations around the GitHub product Discussions. This question should be in the |
Beta Was this translation helpful? Give feedback.
-
|
from collections import defaultdict def count_subarrays_divisible_by_k(arr, k): |
Beta Was this translation helpful? Give feedback.
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
test this with:
print(subarrays_div_by_k([4, 5, 0, -2, -3, 1], 5)) # 7