3917. Count Indices With Opposite Parity
Description
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, andnums[i]andnums[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.
Β
Example 1:
Input: nums = [1,2,3,4]
Output: [2,1,1,0]
Explanation:
nums[0] = 1, which is odd. Thus, the indicesj = 1andj = 3satisfy the conditions, so the score of index 0 is 2.nums[1] = 2, which is even. Thus, the indexj = 2satisfies the conditions, so the score of index 1 is 1.nums[2] = 3, which is odd. Thus, the indexj = 3satisfies the conditions, so the score of index 2 is 1.nums[3] = 4, which is even. Thus, no index satisfies the conditions, so the score of index 3 is 0.
Thus, the answer = [2, 1, 1, 0].
Example 2:
Input: nums = [1]
Output: [0]
Explanation:
There is only one element in nums. Thus, the score of index 0 is 0.
Β
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solutions
Solution 1: Counting
We first count the number of even and odd elements in the array \(\textit{nums}\), denoted as \(cnt[0]\) and \(cnt[1]\) respectively.
Then, we traverse the array \(\textit{nums}\) from left to right. For index \(i\), we first decrement \(cnt[\textit{nums}[i] \bmod 2]\) by 1, then assign \(cnt[\textit{nums}[i] \bmod 2 \oplus 1]\) to \(ans[i]\).
After the traversal, return the answer array \(ans\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\). Ignoring the space complexity of the answer array, the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |