[LeetCode] Count Indices With Opposite Parity

3917. Count Indices With Opposite Parity

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> countOppositeParity(vector<int>& nums) {
vector<int> res(nums.size());
int parity[2]{0,};
for(int i = nums.size() - 1; i >= 0; i--) {
res[i] = parity[!(nums[i]&1)];
parity[nums[i]&1]++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-indices-with-opposite-parity/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.