MediumNo. 2495LeetCode Premium

Number of Subarrays Having Even Product — LeetCode 2495 Python Solution

Topics
Array, Math, Dynamic Programming
Reading time
2 min

The problem

Given a 0-indexed integer array nums, return the number of subarrays of nums having an even product.

Example

Input
nums = [9,6,7,13]
Output
6
Explanation
There are 6 subarrays with an even product:

Python solution

PythonSolution
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

Complexity

Time
O(n)where n is the length of the array `nums`
Space · auxiliary
O(1)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2495. Number of Subarrays Having Even Product is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0313Super Ugly NumberMedium
0368Largest Divisible SubsetMedium
0396Rotate FunctionMedium
0486Predict the WinnerMedium
0553Optimal DivisionMedium
0805Split Array With Same AverageHard

Frequently asked questions

How hard is LeetCode 2495. Number of Subarrays Having Even Product?

LeetCode 2495. Number of Subarrays Having Even Product is rated Medium on LeetCode.

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

The Python solution on this page runs in O(n), where n is the length of the array `nums`.

What is the space complexity of LeetCode 2495. Number of Subarrays Having Even Product?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2495. Number of Subarrays Having Even Product cover?

LeetCode 2495. Number of Subarrays Having Even Product is tagged Array, Math and Dynamic Programming on LeetCode.

Is LeetCode 2495. Number of Subarrays Having Even Product a premium problem?

Yes. LeetCode 2495. Number of Subarrays Having Even Product is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.