You are given an array of integers nums. Write a function to find the number of subarrays that have an equal number of even and odd integers. Please write a function that solves this problem, and explain your algorithm. A key insight is to transform the array (e.g., odd -> 1, even -> -1) and find subarrays that sum to 0.
Assistant
We are asked: "You are given an array of integers nums. Write a function to find the number of subarrays that have an equal number of even and odd integers. Please write a function that solves this problem, and explain your algorithm. A key insight is to transform the array (e.g., odd -> 1, even -> -1) and find subarrays that sum to 0."
We need to produce a solution: write a function that counts the number of subarrays with equal count of even and odd numbers. Use transformation: odd->1, even->-1, then subarray sum zero corresponds to equal number of 1s and -1s, i.e., equal count of odds and evens.
Thus the problem reduces to counting subarrays with sum zero in the transformed array.
Approach: Prefix sum technique with hash map to count frequency of each prefix sum. For each prefix sum value, the number of subarrays ending at current index with sum zero is the count of previous prefix sums equal to current prefix sum. So we maintain a dictionary mapping prefix sum to its frequency. Initialize with prefix sum 0 count = 1 (empty prefix). Iterate, compute prefix sum, add count of same prefix sum to answer, then increment count.
Complexity: O(n) time, O(n) space.
Edge cases: large arrays, values can be negative? But we only care about parity. Actually we transform based on parity; original numbers are integers, we only need even/odd check: if num % 2 == 0 -> even -> -1, else odd -> 1. That's fine.
We'll produce a Python function:
def count_subarrays(nums):
# transform: 1 for odd, -1 for even
# prefix sum, count
count = {0: 1}
prefix = 0
result = 0
for num in nums:
if num % 2 != 0:
prefix += 1
else:
prefix -= 1
# number of subarrays ending here with sum zero = number of previous prefix sums equal to current
result += count.get(prefix, 0)
count[prefix] = count.get(prefix, 0) + 1
return result
Explanation: The transformation yields an array where each element is +1 for odd, -1 for even. For any subarray, the sum of these values equals (number of odds) - (number of evens). We want number of odds = number of evens => sum = 0. So count subarrays with sum zero.
Using prefix sums: Let prefix[i] = sum of first i elements (0-indexed, prefix[0]=0). For subarray from i to j-1 inclusive, sum = prefix[j] - prefix[i]. So sum=0 => prefix[j] = prefix[i]. So for each j, count number of i < j such that prefix[i] == prefix[j]. That's what we accumulate.
Return total.
Complexities: O(n) time, O(n) space.
We'll also provide an example.
We need to output a function and explanation. The user says "Please write a function that solves this problem, and explain your algorithm." So we need to respond with both code and explanation.
We should write the function in a language (probably Python). We'll also discuss correctness and complexity.
I'll produce a clear answer: explanation first, then code. Provide example usage.
Potential pitfalls: careful with even detection: negative even numbers? Parity: num % 2 returns 0 for even, 1 for odd in Python for positive numbers; for negative, -1 % 2 = 1? Actually in Python, -1 % 2 = 1 because -1 = (-1)*2 + 1. So odd negative numbers also give remainder 1. So num % 2 != 0 works for both positive and negative odds. Or use num & 1? But that's okay.
Alternatively we could use num & 1: 1 for odd, 0 for even. But we need -1 for even, so could use 1 if odd else -1.
We'll produce clean code.
Now ensure we handle empty array? The function should return 0 for empty? Actually if array empty, there are no subarrays (or some define empty subarray?). Usually subarray means non-empty contiguous segment. So empty array => 0. Our algorithm: initialize prefix sum 0 count=1 to account for subarray starting at index 0? But if we have empty prefix, then when we compute prefix after first element, we will count the subarray from 0 to index. That's correct. For empty array, we iterate none, result=0, return 0. Good.
So answer ready.
We also need to mention time: O(n), space O(n). Could be optimized to O(n) space.
We'll produce final answer.
Solution Explanation
We need to count all contiguous subarrays where the number of even integers equals the number of odd integers.
Key Insight
Replace each integer with a value that encodes its parity:
odd → +1
even → -1
For a subarray, the sum of these encoded values is
code
(#odd) - (#even)
Thus the subarray has equal numbers of evens and odds iff its sum is zero.
So the problem becomes: count subarrays with sum zero in the transformed array.
Prefix Sum Technique
Let pref[i] be the sum of the first i encoded values (pref[0] = 0).
For a subarray from index l (inclusive) to r (exclusive), its sum is
code
pref[r] - pref[l]
We need pref[r] - pref[l] = 0 → pref[r] = pref[l].
Hence, for each position r we need to know how many earlier prefix sums equal pref[r].
If we store the frequency of each prefix sum seen so far in a hash map, then for the current pref[r] we can immediately add freq[pref[r]] to the answer (all those l produce a zero‑sum subarray ending at r). After counting, we increment freq[pref[r]].
Initialize with freq[0] = 1 because the empty prefix sum 0 occurs once before any element.
Algorithm
code
function count_even_odd_subarrays(nums):
freq = {0: 1} // prefix sum -> frequency
prefix = 0
ans = 0
for each num in nums:
if num is odd:
prefix += 1
else:
prefix -= 1
ans += freq.get(prefix, 0) // all earlier equal prefix sums
freq[prefix] = freq.get(prefix, 0) + 1
return ans
Correctness Proof
We prove that the algorithm returns the exact number of subarrays with equal even and odd counts.
Lemma 1
After processing the first k elements (k ≥ 0), freq contains exactly the number of occurrences of each prefix sum among pref[0], pref[1], ..., pref[k].
Proof.
Initially (k=0) we have freq[0]=1, which matches pref[0]=0.
Inductive step: assume the claim holds after k elements.
When processing element k+1, we compute pref[k+1].
All previous prefix sums stay unchanged, and we then increment freq[pref[k+1]] by 1, adding the new occurrence.
Thus the claim holds for k+1. ∎
Lemma 2
When processing element at index r (0‑based, r from 0 to n-1), the algorithm adds to ans exactly the number of subarrays ending at r that have equal even and odd counts.
Proof.
Consider any subarray ending at r: it is nums[l...r] for some l with 0 ≤ l ≤ r.
Its encoded sum is pref[r+1] - pref[l].
We need pref[r+1] = pref[l].
At the moment we process r, freq contains counts of pref[0] ... pref[r] (by Lemma 1). freq[pref[r+1]] therefore equals the number of indices l in [0, r] with pref[l] = pref[r+1].
Each such l yields a zero‑sum subarray nums[l...r].
The algorithm adds this value to ans. ∎
Lemma 3
All subarrays with equal even and odd counts are counted exactly once.
Proof.
Every such subarray nums[l...r] has pref[l] = pref[r+1].
When the loop reaches r, the prefix sum pref[l] is already in freq (since l ≤ r).
By Lemma 2 the subarray is counted in that step.
It is never counted at any other step because the right endpoint r is unique. ∎
Theorem count_even_odd_subarrays returns the total number of subarrays where the number of even integers equals the number of odd integers.
Proof.
By Lemma 2 the algorithm adds exactly the number of qualifying subarrays ending at each r.
Summing over all r yields the total number.
By Lemma 3 every qualifying subarray is counted exactly once. ∎
Complexity Analysis
Time:O(n) – one pass over the array, each operation is O(1) on average.
Space:O(n) – the hash map may store up to n+1 distinct prefix sums in the worst case.
Reference Implementation (Python 3)
python
def count_even_odd_subarrays(nums):
"""
Returns the number of contiguous subarrays with equal count of even and odd integers.
"""
freq = {0: 1} # prefix sum -> frequency, start with empty prefix
prefix = 0
ans = 0
for num in nums:
# Encode: odd -> +1, even -> -1
if num % 2 != 0: # odd (works for negative numbers as well)
prefix += 1
else:
prefix -= 1
# All earlier prefix sums equal to current give zero-sum subarrays ending here
ans += freq.get(prefix, 0)
# Record current prefix sum occurrence
freq[prefix] = freq.get(prefix, 0) + 1
return ans
# Example usage
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5]
print(count_even_odd_subarrays(arr)) # Output: 4
# Explanation: subarrays [1,2], [2,3], [3,4], [1,2,3,4] have equal evens and odds.
The transformation and prefix‑sum counting give an elegant linear‑time solution.