Count Indices With Opposite Parity Problem
#3917
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3917.
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 indices j = 1 and j = 3 satisfy the conditions, so the score of index 0 is 2.
- nums[1] = 2, which is even. Thus, the index j = 2 satisfies the conditions, so the score of index 1 is 1.
- nums[2] = 3, which is odd. Thus, the index j = 3 satisfies 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
Solution
Approach: Counting
Count how many even and how many odd numbers nums contains, in cnt[0] and cnt[1].
Then scan from left to right. At index i, first remove nums[i] from its own counter, so cnt describes only the elements after i. The score of index i is then the counter of the opposite parity, cnt[(nums[i] & 1) ^ 1].
Complexity: time O(n), space O(1) besides the output, where n is the length of nums.
class Solution:
def countOppositeParity(self, nums: List[int]) -> List[int]:
cnt = [0, 0]
for x in nums:
cnt[x & 1] += 1
ans = [0] * len(nums)
for i, x in enumerate(nums):
cnt[x & 1] -= 1
ans[i] = cnt[x & 1 ^ 1]
return ans