Number of Subarrays Having Even Product - Problem

Given a 0-indexed integer array nums, your task is to find and return the number of subarrays whose product of all elements is even.

A subarray is a contiguous sequence of elements within an array. For example, in array [1,2,3,4], some subarrays are [1,2], [2,3,4], and [1,2,3,4].

The product of a subarray is even if it contains at least one even number, since any number multiplied by an even number results in an even product.

Goal: Count all possible subarrays with even products efficiently.

Input & Output

example_1.py โ€” Basic Case
$ Input: [2,1,3,4]
โ€บ Output: 7
๐Ÿ’ก Note: The subarrays with even products are: [2], [2,1], [2,1,3], [2,1,3,4], [1,3,4], [3,4], [4]. All contain at least one even number, making their products even.
example_2.py โ€” All Odd Numbers
$ Input: [1,3,5]
โ€บ Output: 0
๐Ÿ’ก Note: All numbers are odd, so every subarray contains only odd numbers. The product of odd numbers is always odd, resulting in 0 subarrays with even products.
example_3.py โ€” All Even Numbers
$ Input: [2,4,6]
โ€บ Output: 6
๐Ÿ’ก Note: All numbers are even, so every possible subarray has an even product. Total subarrays = n*(n+1)/2 = 3*4/2 = 6: [2], [4], [6], [2,4], [4,6], [2,4,6].

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • Note: Numbers can be very large, but we only care about their parity (odd/even)

Visualization

Tap to expand
๐Ÿช Cookie Factory Quality ControlConveyor BeltChocolate Chip(Even: 2)Plain(Odd: 1)Plain(Odd: 3)Chocolate Chip(Even: 4)Plain Cookie SegmentLength: 2 cookiesQuality Control Calculation1. Total possible cookie groups = 4 ร— 5 รท 2 = 102. Plain cookie segment [1,3] has length 23. Plain groups in segment = 2 ร— 3 รท 2 = 3 โ€ข Single groups: [1], [3] โ€ข Pair group: [1,3]4. Premium groups = Total - Plain = 10 - 3 = 7โœ“ Result: 7 premium cookie groups!
Understanding the Visualization
1
Identify Plain Cookie Segments
Scan the conveyor belt and mark consecutive plain cookies (odd numbers)
2
Count Segment Groups
For each plain cookie segment of length k, it contains k*(k+1)/2 possible groups
3
Sum All Plain Groups
Add up all the plain cookie groups from all segments
4
Calculate Premium Groups
Total possible groups minus plain groups equals premium groups (with chocolate chips)
Key Takeaway
๐ŸŽฏ Key Insight: Rather than checking every possible group for chocolate chips, we efficiently count the rare 'all plain' groups and subtract from the total. This mathematical approach transforms an O(nยณ) problem into an elegant O(n) solution!
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.2K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen