Lv.1arraymathprefix-sum
Subarrays with an Odd Sum
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 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
| nums | result |
|---|---|
[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
-
nums.length -
nums[i] - The answer may not fit in 32 bits; use a 64-bit integer (
long).
Expected complexity
- Time
- O(N)
- Space
- O(1)
Examples
| nums | Expected |
|---|---|
[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 and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1102 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 3 | verdict only |