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 <= 1051 <= nums[i] <= 1091 <= target <= 109Problem Overview: You are given an integer array and need to count subarrays where some element appears strictly more than half of the subarray length (a majority element). The challenge is detecting majority dominance across all possible subarrays without checking every frequency from scratch.
Approach 1: Brute Force Frequency Check (O(n^3) time, O(1) space)
Enumerate every subarray using two nested loops. For each range [l, r], compute element frequencies and check whether any count exceeds (r - l + 1) / 2. This requires scanning the subarray or maintaining a temporary frequency map. While straightforward, it performs a full validation for every possible range and quickly becomes impractical as n grows.
Approach 2: Prefix Frequency + Candidate Tracking (O(n^2) time, O(n) space)
Instead of recomputing frequencies from scratch, maintain incremental counts while expanding the right boundary of a subarray. A hash table tracks element frequencies and updates the current maximum frequency as the window grows. This removes the inner scan but still requires evaluating O(n^2) subarrays. It demonstrates the key observation: majority depends on comparing frequency against half of the window length.
Approach 3: Prefix Balance + Binary Indexed Tree (O(n log n) time, O(n) space)
The optimized approach converts the majority condition into a prefix comparison problem. For a candidate value, map occurrences to +1 and all other values to -1. A subarray has that value as majority if the prefix sum difference between its boundaries is positive. Counting such ranges reduces to counting pairs of prefix sums where the later sum is greater than the earlier one.
A Binary Indexed Tree (Fenwick Tree) efficiently counts how many previous prefix sums are smaller than the current value. Use coordinate compression because prefix values may be negative. Iterate through prefix sums, query the Fenwick Tree for counts of smaller values, then update the tree with the current prefix. This transforms the problem into an inversion-style counting task.
This technique combines prefix sum transformations with efficient frequency queries using a Fenwick Tree. The same idea appears in advanced range-counting problems involving arrays and can also be implemented with divide-and-conquer techniques similar to segment tree or merge-sort based counting.
Recommended for interviews: Interviewers expect the prefix transformation plus Binary Indexed Tree approach. Starting with brute force shows understanding of the majority condition, but moving to prefix sums and Fenwick Tree demonstrates algorithmic maturity and knowledge of range counting techniques.
According to the problem description, we can treat elements equal to target in the array as 1, and elements not equal to target as -1. This way, target being the majority element of a subarray is equivalent to the number of 1s in the subarray being strictly greater than the number of -1s, 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 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 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.
Python
Java
C++
Go
TypeScript
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Frequency Check | O(n^3) | O(1) | Conceptual baseline or very small arrays |
| Incremental Frequency Tracking | O(n^2) | O(n) | Improves brute force by reusing frequency counts |
| Prefix Sum + Binary Indexed Tree | O(n log n) | O(n) | Optimal general solution for large inputs |
Q4. Count Subarrays With Majority Element II | O(nlogn) Policy Based Data Structure | Biweekly 169🚀 • Rajan Keshari ( CSE - IIT Dhanbad ) • 1,069 views views
Watch 2 more video solutions →Practice Count Subarrays With Majority Element II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor