Number of Subarrays Having Even Product Problem
#2495
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2495.
Given a 0-indexed integer array nums, return the number of subarrays of nums having an even product.
Example 1:
Input: nums = [9,6,7,13]
Output: 6
Explanation: There are 6 subarrays with an even product:
- nums[0..1] = 9 * 6 = 54.
- nums[0..2] = 9 * 6 * 7 = 378.
- nums[0..3] = 9 * 6 * 7 * 13 = 4914.
- nums[1..1] = 6.
- nums[1..2] = 6 * 7 = 42.
- nums[1..3] = 6 * 7 * 13 = 546.
Example 2:
Input: nums = [7,3,5]
Output: 0
Explanation: There are no subarrays with an even product.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Count by the last even number
A product is even exactly when the subarray holds at least one even number. Scan left to right and remember last, the index of the latest even number (-1 if none yet). The subarrays ending at the current index that contain an even number are those starting at 0..last, which is last + 1 of them. Add that for every index.
Complexity: time O(n); space O(1).
class Solution:
def evenProduct(self, nums: List[int]) -> int:
ans, last = 0, -1
for i, v in enumerate(nums):
if v % 2 == 0:
last = i
ans += last + 1
return ans