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βββββββ5
1 <= nums[i] <= 10βββββββ9
1 <= target <= 109
Solutions
Solution 1: Binary Indexed Tree
According to the problem description, we can treat elements equal to \(\textit{target}\) in the array as \(1\), and elements not equal to \(\textit{target}\) as \(-1\). This way, \(\textit{target}\) being the majority element of a subarray is equivalent to the number of \(1\)s in the subarray being strictly greater than the number of \(-1\)s, i.e., the sum of the subarray is strictly greater than \(0\).
We can enumerate subarrays ending at each position. Let the prefix sum at the current position be \(\textit{s}\). Then the number of subarrays ending at this position with a sum greater than \(0\) is equivalent to the count of prefix sums that are less than \(\textit{s}\). We can use a Binary Indexed Tree to maintain the occurrence count of prefix sums, allowing us to efficiently calculate the answer. The range of prefix sums is \([-n, n]\). We can shift all prefix sums right by \(n+1\) units to transform the range to \([1, 2n+1]\).
The time complexity is \(O(n \log n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array.