Skip to content

2495. Number of Subarrays Having Even Product 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  long long evenProduct(vector<int>& nums) {
    long ans = 0;
    int numsBeforeEven = 0;  // inclusively

    // e.g. nums = [1, 0, 1, 1, 0].
    // After meeting the first 0, set `numsBeforeEven` to 2. So, the number
    // between index 1 to index 3 (the one before next 0) will contribute 2 to
    // `ans`.
    for (int i = 0; i < nums.size(); ++i) {
      if (nums[i] % 2 == 0)
        numsBeforeEven = i + 1;
      ans += numsBeforeEven;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public long evenProduct(int[] nums) {
    long ans = 0;
    int numsBeforeEven = 0; // inclusively

    // e.g. nums = [1, 0, 1, 1, 0].
    // After meeting the first 0, set `numsBeforeEven` to 2. So, the number
    // between index 1 to index 3 (the one before next 0) will contribute 2 to
    // `ans`.
    for (int i = 0; i < nums.length; ++i) {
      if (nums[i] % 2 == 0)
        numsBeforeEven = i + 1;
      ans += numsBeforeEven;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def evenProduct(self, nums: list[int]) -> int:
    ans = 0
    numsBeforeEven = 0  # inclusively

    # e.g. nums = [1, 0, 1, 1, 0].
    # After meeting the first 0, set `numsBeforeEven` to 2. So, the number
    # between index 1 to index 3 (the one before next 0) will contribute 2 to
    # `ans`.
    for i, num in enumerate(nums):
      if num % 2 == 0:
        numsBeforeEven = i + 1
      ans += numsBeforeEven

    return ans