Problem Description
Given an integer array nums, count and return the number of subarrays such that the product of all elements in the subarray is even. A subarray is a contiguous segment of the array. The product is even if at least one element in the subarray is even.
Key Insights
- A product is even if and only if at least one even number is present.
- Count total subarrays using the formula n*(n+1)/2.
- Count subarrays with all odd numbers (none of which contribute an even factor) by grouping contiguous odd segments and summing L*(L+1)/2 for each.
- Result equals total subarrays minus the count of all-odd subarrays.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We solve the problem by first calculating the total number of subarrays by using the formula n*(n+1)/2 for an array of length n. Next, we iterate over the array to count all contiguous segments that consist only of odd numbers. For each segment, we calculate the number of subarrays contained in that segment using L*(L+1)/2 where L is the length of the segment. Since these subarrays never include an even number, their product is odd. Finally, subtract this count from the total subarrays to get the desired number of subarrays with an even product. The algorithm leverages simple iteration, arithmetic, and minimal extra space.