Count Smaller Elements With Opposite Parity Problem
#3907
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 3907.
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 < nnums[j] < nums[i]nums[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 = [5,2,4,1,3]
Output: [2,1,2,0,0]
Explanation:
- For i = 0, the elements nums[1] = 2 and nums[2] = 4 are smaller and have different parity.
- For i = 1, the element nums[3] = 1 is smaller and has different parity.
- For i = 2, the elements nums[3] = 1 and nums[4] = 3 are smaller and have different parity.
- No valid elements exist for the remaining indices.
Thus, the answer = [2, 1, 2, 0, 0].
Example 2:
Input: nums = [4,4,1]
Output: [1,1,0]
Explanation:
For i = 0 and i = 1, the element nums[2] = 1 is smaller and has different parity. Thus, the answer = [1, 1, 0].
Example 3:
Input: nums = [7]
Output: [0]
Explanation:
No elements exist to the right of index 0, so its score is 0. Thus, the answer = [0].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Binary Indexed Tree
Scan the array from right to left and keep two Binary Indexed Trees (Fenwick trees) over the compressed values: one for the even numbers seen so far and one for the odd numbers.
For nums[i], query the tree of the opposite parity for how many stored values are smaller than nums[i]. That count is answer[i]. Then add nums[i] to the tree of its own parity.
Complexity: time O(n log n), space O(n), where n is the length of the array.
from bisect import bisect_left
class BinaryIndexedTree:
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x > 0:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countSmallerOppositeParity(self, nums: List[int]) -> List[int]:
n = len(nums)
sorted_nums = sorted(set(nums))
m = len(sorted_nums)
bits = [BinaryIndexedTree(m), BinaryIndexedTree(m)]
ans = [0] * n
for i in range(n - 1, -1, -1):
x = bisect_left(sorted_nums, nums[i]) + 1
ans[i] = bits[nums[i] & 1 ^ 1].query(x - 1)
bits[nums[i] & 1].update(x, 1)
return ans