#3917
Easy Algorithms Count indices with opposite parity
81.6% acceptance
May 13, 2026
23
1
You are given an integer array nums of length n.
The score of an index i is defined as the number of indices j such that:
i < j < n, and
nums[i] and nums[j] have different parity (one is even and the other is odd).
Return an integer array answer of length n, where answer[i] is the score of index i.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn count_opposite_parity(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut suffix_even = 0i32;
let mut suffix_odd = 0i32;
let mut ans = vec![0i32; n];
for i in (0..n).rev() {
ans[i] = if nums[i] % 2 == 0 { suffix_odd } else { suffix_even };
if nums[i] % 2 == 0 { suffix_even += 1; } else { suffix_odd += 1; }
}
ans
}
}