Skip to main content
Back to problems
#2495
Medium Algorithms

Number of subarrays having even product

Array Math Dynamic Programming
63.2% acceptance
Mar 31, 2026
54
5
Given a 0-indexed integer array nums, return the number of subarrays of nums having an even product.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn even_product(nums: Vec<i32>) -> i64 {
    let n = nums.len() as i64;
    let total = n * (n + 1) / 2;
    let mut odd_count = 0i64;
    let mut streak = 0i64;
    for &x in &nums {
      if x % 2 == 1 {
        streak += 1;
      } else {
        odd_count += streak * (streak + 1) / 2;
        streak = 0;
      }
    }
    odd_count += streak * (streak + 1) / 2;
    total - odd_count
  }
}