aboutsummaryrefslogtreecommitdiff
path: root/subarr_sums_div_k.py
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /subarr_sums_div_k.py
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'subarr_sums_div_k.py')
-rw-r--r--subarr_sums_div_k.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/subarr_sums_div_k.py b/subarr_sums_div_k.py
new file mode 100644
index 0000000..c946fc7
--- /dev/null
+++ b/subarr_sums_div_k.py
@@ -0,0 +1,29 @@
+# 974. Subarray Sums Divisible by K
+
+"""
+given an integer array 'nums' and an integer 'k', return the number of non
+empty subarrays that have a sum divisible by 'k'. a subarray is contiguous
+part of an array.
+"""
+
+
+class Solution(object):
+ def subarraysDivByK(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: int
+ """
+ ans, prefix = 0, 0
+ cnt = [1] + [0] * k
+ for i in nums:
+ prefix = (prefix + i) % k
+ ans += cnt[prefix]
+ cnt[prefix] += 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.subarraysDivByK(nums=[4, 5, 0, -2, -3, 1], k=5))
+ print(obj.subarraysDivByK(nums=[5], k=9))