Suppose we have an array arr. We have to find the number of sub-arrays with odd sum. If the answer is too large then return result modulo 10^9+7.
So, if the input is like arr = [8,3,7], then the output will be 3 because all sub arrays are [[8],[3],[7],[8,3],[3,7],[8,3,7]] Now their sum values are [8,3,7,11,10,18] so there are three odd sum values [3,7,11].
To solve this, we will follow these steps −
freq := a list with two elements 1 and 0
ans := 0
prefix := 0
for each x in arr, do
prefix := prefix + x
ans := ans + freq[1 XOR prefix AND 1]
freq[prefix AND 1] := freq[prefix AND 1] + 1
return ans mod (10^9+7)
Let us see the following implementation to get better understanding −
Example
def solve(arr): freq = [1, 0] ans = prefix = 0 for x in arr: prefix += x ans += freq[1 ^ prefix&1] freq[prefix &s; 1] += 1 return ans % (10**9+7) arr = [8,3,7] print(solve(arr))
Input
[8,3,7]
Output
3