Funcia
Lv.1arraymathprefix-sum

Subarrays with an Odd Sum

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Given an integer array nums, return the number of non-empty contiguous subarrays nums[l..r] whose sum is odd. Subarrays are distinguished by their positions.

Examples

numsresult
[1, 3, 5]4
[2, 4, 6]0
[1, 2, 3, 4, 5, 6, 7]16

Example 1 — the subarray sums are 1, 3, 5, 4, 8, 9; four of them are odd.

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[]) → long

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000
  • −109≤-10^9 \le nums[i] ≤109\le 10^9
  • The answer may not fit in 32 bits; use a 64-bit integer (long).

Expected complexity

Time
O(N)
Space
O(1)

Examples

numsExpected
[1,3,5]4
[2,4,6]0
[1,2,3,4,5,6,7]16

Hint

Hint

With prefix sums P, the subarray nums[l..r] sums to P[r+1] - P[l], which is odd exactly when the two prefix sums have different parity. Count even and odd prefix sums seen so far; each new prefix adds the count of the opposite parity. Beware that x % 2 can be -1 for negative numbers in some languages. Checking every subarray is O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251102 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance603verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.