aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-02-24 20:14:35 -0700
committerJack Sangdahl <[email protected]>2025-02-24 20:14:35 -0700
commit658556f3d4eaa1cdefd7009e7b6ccb3cabcd31ac (patch)
tree789c0f7874ff9d86e0f11e16daa5e15f0ed73e44
parentf86f165d87dacea43fb73a7f4106b3e3dbc3d83e (diff)
downloadleetcode-658556f3d4eaa1cdefd7009e7b6ccb3cabcd31ac.tar.gz
leetcode-658556f3d4eaa1cdefd7009e7b6ccb3cabcd31ac.zip
1524. number of subarrays with odd sum
-rw-r--r--number_subarr_odd_sum.c24
-rw-r--r--number_subarr_odd_sum.py28
2 files changed, 52 insertions, 0 deletions
diff --git a/number_subarr_odd_sum.c b/number_subarr_odd_sum.c
new file mode 100644
index 0000000..bcc1569
--- /dev/null
+++ b/number_subarr_odd_sum.c
@@ -0,0 +1,24 @@
+// 1524. Number of Sub-arrays With Odd Sum
+#include "leetcode.h"
+
+/*
+ * given an array of integers 'arr', return the number of subarrays with an odd
+ * sum. since the answer can be very large, return it modulo 10e9+7.
+ */
+
+int numOfSubarrays(int *arr, int arrSize) {
+ int curr = 0, ans = 0, cnt[] = {1, 0}, mod = 1e9 + 7;
+ for (int i = 0; i < arrSize; i++) {
+ curr ^= arr[i] & 1;
+ ans = (ans + cnt[1 - curr]) % mod;
+ cnt[curr]++;
+ }
+ return ans;
+}
+
+int main() {
+ int a1[] = {1, 3, 5}, a2[] = {2, 4, 6}, a3[] = {1, 2, 3, 4, 5, 6, 7};
+ printf("%d\n", numOfSubarrays(a1, ARRAY_SIZE(a1))); // expect: 4
+ printf("%d\n", numOfSubarrays(a2, ARRAY_SIZE(a2))); // expect: 0
+ printf("%d\n", numOfSubarrays(a3, ARRAY_SIZE(a3))); // expect: 16
+}
diff --git a/number_subarr_odd_sum.py b/number_subarr_odd_sum.py
new file mode 100644
index 0000000..cf00796
--- /dev/null
+++ b/number_subarr_odd_sum.py
@@ -0,0 +1,28 @@
+# 1524. Number of Sub-arrays With Odd Sum
+
+"""
+given an array of integers 'arr', return the number of subarrays with an odd
+sum. since the answer can be very large, return it modulo 10e9+7.
+"""
+
+
+class Solution(object):
+ def numOfSubarrays(self, arr):
+ """
+ :type arr: List[int]
+ :rtype: int
+ """
+ cnt = [1, 0]
+ curr, ans = 0, 0
+ for i in arr:
+ curr ^= i & 1
+ ans += cnt[1 - curr]
+ cnt[curr] += 1
+ return ans % (10**9 + 7)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numOfSubarrays(arr=[1, 3, 5]))
+ print(obj.numOfSubarrays(arr=[2, 4, 6]))
+ print(obj.numOfSubarrays(arr=[1, 2, 3, 4, 5, 6, 7]))