LeetCode 2495: Number of Subarrays Having Even Product Solution

Master LeetCode problem 2495 (Number of Subarrays Having Even Product), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2495. Number of Subarrays Having Even Product

Problem Explanation

Explanation:

To solve this problem, we can iterate through the array and keep track of the number of subarrays with even product. We can do this by maintaining a count of the number of odd and even elements encountered so far.

For any subarray to have an even product, it must have an even number of odd elements. We can keep track of the count of odd elements encountered so far.

As we iterate through the array, we count the number of odd and even elements. For each new element, we update the count of odd and even elements. Whenever we encounter an odd element, we increment the count of odd elements and calculate the number of subarrays that can be formed with even product using the count of odd elements.

The total number of subarrays with even product will be the sum of the counts of subarrays with even product calculated for each element.

Time complexity: O(N), where N is the number of elements in the array. Space complexity: O(1)

:

Solution Code

class Solution {
    public int numSubarraysWithEvenProduct(int[] nums) {
        int count = 0;
        int oddCount = 0;
        int result = 0;
        
        for (int num : nums) {
            if (num % 2 == 1) {
                oddCount++;
                count = 0;
            } else {
                count++;
                result += oddCount;
            }
            result += count;
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2495 (Number of Subarrays Having Even Product)?

This page provides optimized solutions for LeetCode problem 2495 (Number of Subarrays Having Even Product) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2495 (Number of Subarrays Having Even Product)?

The time complexity for LeetCode 2495 (Number of Subarrays Having Even Product) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2495 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2495 in Java, C++, or Python.

Back to LeetCode Solutions