Number of Subarrays Having Even Product - Problem

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

A subarray is a contiguous non-empty sequence of elements within an array. The product of a subarray is even if it contains at least one even number.

Input & Output

Example 1 — Mixed Even/Odd
$ Input: nums = [2,1,4,3,6]
Output: 13
💡 Note: Total subarrays: 15. Odd-only subarrays: [1] and [3] = 2. Even product subarrays: 15 - 2 = 13
Example 2 — All Odd
$ Input: nums = [1,3,5]
Output: 0
💡 Note: All numbers are odd, so no subarray can have an even product. Result is 0
Example 3 — All Even
$ Input: nums = [2,4,6]
Output: 6
💡 Note: All subarrays contain at least one even number, so all 6 subarrays have even product

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Number of Subarrays Having Even Product INPUT nums = [2, 1, 4, 3, 6] 2 EVEN 1 ODD 4 EVEN 3 ODD 6 EVEN i=0 i=1 i=2 i=3 i=4 Total Subarrays n*(n+1)/2 = 5*6/2 = 15 Even number Odd number Array length n = 5 Find subarrays with even product (contains at least 1 even) ALGORITHM STEPS 1 Count Odd-Only Subarrays Track consecutive odd numbers 2 For each odd streak Count = k*(k+1)/2 subarrays 3 Sum all odd subarrays oddCount = sum of all streaks 4 Subtract from total Result = total - oddCount Odd Streaks Analysis [2] 1 [4] 3 [6] Even breaks Streak at i=1: k=1 1*2/2=1 Streak at i=3: k=1 1*2/2=1 Odd subarrays: 1+1 = 2 Even = 15 - 2 = 13 FINAL RESULT Even Product Subarrays 13 Calculation Summary Total subarrays: 15 Odd-only subarrays: 2 Even subarrays: 13 Sample Even Subarrays [2] [2,1] [2,1,4] [4] [1,4] [4,3,6] [6] [3,6] [4,3] ... and 4 more OK - Output: 13 Key Insight: Instead of counting subarrays with even product directly, count subarrays with only odd numbers (all-odd product). A subarray has even product if it contains at least one even number. Formula: EvenSubarrays = TotalSubarrays - OddOnlySubarrays = n(n+1)/2 - sum of k(k+1)/2 for each odd streak TutorialsPoint - Number of Subarrays Having Even Product | Count Odd-Only Subarrays Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 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