Leetcode 1524: Number of Sub-arrays With Odd Sum

grid47
grid47
Exploring patterns and algorithms
Jun 7, 2024 5 min read

You are given an array of integers arr. Your task is to count the number of subarrays whose sum is odd. Since the answer can be a large number, return it modulo (10^9 + 7).
Problem
Approach
Steps
Complexity
Input: An array of integers `arr` is given as input.
Example: arr = [1, 3, 5]
Constraints:
• 1 <= arr.length <= 10^5
• 1 <= arr[i] <= 100
Output: Return the number of subarrays whose sum is odd, modulo (10^9 + 7).
Example: For arr = [1, 3, 5], the output is 4.
Constraints:
• The output is the number of subarrays with an odd sum modulo (10^9 + 7).
Goal: Count the number of subarrays with odd sums.
Steps:
• Iterate through the array and track the odd and even subarray sums.
• Swap the odd and even counts when an odd number is encountered.
• Sum the odd subarrays and return the result modulo (10^9 + 7).
Goal: The input size can be large, and the values of elements in the array can also be large.
Steps:
• 1 <= arr.length <= 10^5
• 1 <= arr[i] <= 100
Assumptions:
• The array is not empty and contains at least one element.
• The array contains integers within the given range.
Input: arr = [1, 3, 5]
Explanation: The subarrays are [1], [1, 3], [1, 3, 5], [3], [3, 5], [5]. Their sums are [1, 4, 9, 3, 8, 5], and the odd sums are [1, 9, 3, 5]. Thus, the answer is 4.

Input: arr = [2, 4, 6]
Explanation: All subarrays have even sums, so there are no odd-sum subarrays. Thus, the answer is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus