Count Subarrays With Majority Element II Problem
Description
LeetCode Problem 3739.
You are given an integer array nums and an integer target.
Return the number of subarrays of nums in which target is the majority element.
The majority element of a subarray is the element that appears strictly more than half of the times in that subarray.
Example 1:
Input: nums = [1,2,2,3], target = 2
Output: 5
Explanation:
Valid subarrays with target = 2 as the majority element:
- nums[1..1] = [2]
- nums[2..2] = [2]
- nums[1..2] = [2,2]
- nums[0..2] = [1,2,2]
- nums[1..3] = [2,2,3]
So there are 5 such subarrays.
Example 2:
Input: nums = [1,1,1,1], target = 1
Output: 10
Explanation:
All 10 subarrays have 1 as the majority element.
Example 3:
Input: nums = [1,2,3], target = 4
Output: 0
Explanation:
target = 4 does not appear in nums at all. Therefore, there cannot be any subarray where 4 is the majority element. Hence the answer is 0.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= target <= 10^9
Solution
Approach: Prefix sums and a Fenwick tree
Map every element equal to target to +1 and every other element to -1. A subarray has target as its majority exactly when its sum is greater than 0.
With prefix sums, the subarray ending at the current position has a positive sum when some earlier prefix sum is smaller than the current one s. So for each position we add the number of earlier prefix sums that are < s, then record s. A Fenwick tree (binary indexed tree) over the sums, shifted by n + 1 to stay positive, answers these counts and updates in O(log n).
Complexity: time O(n log n), space O(n).
class BinaryIndexedTree:
__slots__ = "n", "c"
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:
s += self.c[x]
x -= x & -x
return s
class Solution:
def countMajoritySubarrays(self, nums: List[int], target: int) -> int:
n = len(nums)
tree = BinaryIndexedTree(n * 2 + 1)
s = n + 1
tree.update(s, 1)
ans = 0
for x in nums:
s += 1 if x == target else -1
ans += tree.query(s - 1)
tree.update(s, 1)
return ans