703390. Find the number of subarrays having even sum

Medium

Here is a detailed Markdown blog post for the problem:

Find the number of subarrays having even sum #1533

Summary

This problem involves finding the number of subarrays in an array that have an even sum. The given array can contain both positive and negative integers, and we need to count the number of subarrays that have a total sum divisible by 2.

The key concepts involved are arrays, data structures, and algorithms.

Detailed Explanation

To solve this problem, we will iterate over all possible subarrays in the given array. For each subarray, we calculate its sum and check if it's even (i.e., divisible by 2). If the sum is even, we increment a counter to keep track of the number of such subarrays.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable count to store the number of subarrays with even sums.
  2. Iterate over all possible subarrays in the given array. For each subarray:
    • Calculate its sum by iterating over its elements and adding them up.
    • Check if the sum is even (i.e., divisible by 2).
    • If the sum is even, increment the count variable.
  3. Return the final value of the count variable as the number of subarrays with even sums.

Time complexity: O(n^2), where n is the length of the given array. This is because we're iterating over all possible subarrays in the array, and each subarray has a maximum size of n. Space complexity: O(1), as we only need to keep track of a single variable count.

Here's an ASCII art diagram illustrating the problem:

       +---------------+
       |  Array [a, b, c] |
       +---------------+
                  |
                  v
+---------------+       +---------------+
|  Subarray [a]  |       |  Subarray [b]  |
|  (sum = a)      |       |  (sum = b)      |
+---------------+       +---------------+
                  |
                  v
+---------------+       +---------------+
|  Subarray [a, b]|       |  Subarray [c]  |
|  (sum = a+b)    |       |  (sum = c)      |
+---------------+       +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
public int findSubarrays(int[] arr) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
        for (int j = i; j < arr.length; j++) {
            int sum = 0;
            for (int k = i; k <= j; k++) {
                sum += arr[k];
            }
            if (sum % 2 == 0) {
                count++;
            }
        }
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.