BackhardArrays

Subarrays with Sum Equal to Even Count Solution

Problem Statement

Given an array of integers `nums`, find the total number of contiguous subarrays where the sum of the elements is exactly equal to the count of even elements in that subarray. An integer `x` is considered even if `x % 2 == 0` (this includes negative even integers and zero).

Example 1
Input
nums = [1, 2, 0]
Output
1

Explanation: Let's analyze all contiguous subarrays: - [1]: sum = 1, even count = 0 (1 != 0) - [2]: sum = 2, even count = 1 (2 != 1) - [0]: sum = 0, even count = 1 (0 != 1) - [1, 2]: sum = 3, even count = 1 (3 != 1) - [2, 0]: sum = 2, even count = 2 (2 == 2) -> Valid - [1, 2, 0]: sum = 3, even count = 2 (3 != 2) There is exactly 1 valid subarray.

Example 2
Input
nums = [0, 2, 0]
Output
2

Explanation: The valid contiguous subarrays are: 1. [0, 2] (from index 0 to 1): sum = 2, even count = 2 (2 == 2) 2. [2, 0] (from index 1 to 2): sum = 2, even count = 2 (2 == 2) Thus, there are 2 valid subarrays.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free