Skip to content

1524. Number of Sub-arrays With Odd Sum

Description

Given an array of integers arr, return the number of subarrays with an odd sum.

Since the answer can be very large, return it modulo 109 + 7.

 

Example 1:

Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.

Example 2:

Input: arr = [2,4,6]
Output: 0
Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.

Example 3:

Input: arr = [1,2,3,4,5,6,7]
Output: 16

 

Constraints:

  • 1 <= arr.length <= 105
  • 1 <= arr[i] <= 100

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(n)
  • Space complexity: O(n)

 

JavaScript

js
/**
 * @param {number[]} arr
 * @return {number}
 */
const numOfSubarrays = function (arr) {
  const MODULO = 10 ** 9 + 7;
  const size = arr.length;
  const dp = new Array(size + 1)
    .fill('')
    .map(_ => ({ odd: 0, even: 0 }));
  let result = 0;

  for (let index = 1; index <= size; index++) {
    const value = arr[index - 1];

    if (value % 2) {
      dp[index].odd = dp[index - 1].even + 1;
      dp[index].even = dp[index - 1].odd;
    } else {
      dp[index].odd = dp[index - 1].odd;
      dp[index].even = dp[index - 1].even + 1;
    }
    result += dp[index].odd;
  }
  return result % MODULO;
};

Released under the MIT license