KatInterview

Subarrays with Odd Zero Frequency

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingprefix-sumtwo-pointersmath

Last updated

Tests understanding of prefix parity tracking and combinatorial counting to efficiently solve subarray problems.

You're given an integer array nums. Your task is to determine how many contiguous subarrays contain an odd number of zeros.

A subarray is a contiguous non-empty slice of the array. For example, in [1, 0, 2], the subarrays are [1], [0], [2], [1, 0], [0, 2], and [1, 0, 2].

Return the total count of subarrays where the number of zeros is odd (1, 3, 5, etc.).

Constraints

  • 1 <= nums.length <= 100,000
  • -10^9 <= nums[i] <= 10^9
  • Your solution should run in O(n) time

Examples

Example 1

Input: count_odd_zero_subarrays([0, 0, 1, 0, 1])

Output: 9

Example 2

Input: count_odd_zero_subarrays([1, 2, 3])

Output: 0

Example 3

Input: count_odd_zero_subarrays([0])

Output: 1

Example 4

Input: count_odd_zero_subarrays([0, 1, 0, 0])

Output: 6

Hints

Hint 1

Think about the parity (even or odd) of zero counts in prefixes rather than the actual counts themselves.

Hint 2

A subarray from index i to j has an odd zero count if and only if the prefix ending at j and the prefix ending before i have different parities.

Hint 3

Track how many prefixes have even parity and how many have odd parity as you scan through the array.