aboutsummaryrefslogtreecommitdiff
path: root/subarr_sums_div_k.c
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.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'subarr_sums_div_k.c')
-rw-r--r--subarr_sums_div_k.c30
1 files changed, 30 insertions, 0 deletions
diff --git a/subarr_sums_div_k.c b/subarr_sums_div_k.c
new file mode 100644
index 0000000..46dce84
--- /dev/null
+++ b/subarr_sums_div_k.c
@@ -0,0 +1,30 @@
+// 974. Subarray Sums Divisible by K
+#include "leetcode.h"
+
+/*
+ * 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.
+ */
+
+int subarraysDivByK(int *nums, int numsSize, int k) {
+ int n = numsSize, sum = 0, ans = 0;
+ int *hash = (int *)calloc(k, sizeof(int));
+ hash[0] = 1;
+ for (int i = 0; i < n; i++) {
+ sum += nums[i];
+ int val = sum + 10000 * k;
+ while (val < 0)
+ val += k;
+ ans += hash[val % k];
+ hash[val % k]++;
+ }
+ free(hash);
+ return ans;
+}
+
+int main() {
+ int n1[] = {4, 5, 0, -2, -3, 1}, n2[] = {5};
+ printf("%d\n", subarraysDivByK(n1, ARRAY_SIZE(n1), 5)); // expect: 7
+ printf("%d\n", subarraysDivByK(n2, ARRAY_SIZE(n2), 9)); // expect: 0
+}