Skip to main content

Count Subarrays With Majority Element II - Solution & Explanation

HardArrayHash TableDivide and ConquerSegment Tree10 min readAsked at: Amazon, Microsoft
Practice this problem

Problem Statement

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

Approach Overview

Problem 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.

Solution

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Frequency CheckO(n^3)O(1)Conceptual baseline or very small arrays
Incremental Frequency TrackingO(n^2)O(n)Improves brute force by reusing frequency counts
Prefix Sum + Binary Indexed TreeO(n log n)O(n)Optimal general solution for large inputs

Video Solution

Count Subarrays With Majority Element I and II | 5 Approaches | Leetcode 3737 and 3739 | MIK • codestorywithMIK • 18,602 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Subarrays With Majority Element II easy or hard?
The problem is classified as Hard because it requires transforming a majority condition into a prefix inequality and then counting valid ranges efficiently. Understanding Fenwick Trees or divide-and-conquer counting is usually necessary to reach the optimal solution.
Count Subarrays With Majority Element II Python/Java solution
Python, Java, C++, Go, and TypeScript implementations typically follow the same pattern: compute prefix sums, compress their values, and use a Fenwick Tree to query how many earlier prefixes are smaller. Each iteration updates the tree with the current prefix index.
How to solve Count Subarrays With Majority Element II in O(n log n)?
Transform the array into a prefix balance where the target element contributes +1 and all others contribute -1. A subarray has a majority when its prefix difference is positive. Use coordinate compression and a Binary Indexed Tree to count how many previous prefix sums are smaller than the current prefix while scanning the array.
What is the best approach for Count Subarrays With Majority Element II?
The most efficient method uses a prefix sum transformation combined with a Binary Indexed Tree (Fenwick Tree). Convert the majority condition into a prefix balance problem and count valid prefix pairs using Fenwick Tree queries. This reduces the complexity to O(n log n) with O(n) extra space.
Is Count Subarrays With Majority Element II asked at Google/Amazon/Meta?
Majority-element and prefix-sum counting problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving prefix sums, Fenwick Trees, or merge-sort counting are common in hard-level algorithm rounds.
What data structure is used in Count Subarrays With Majority Element II?
The key data structure is a Binary Indexed Tree (Fenwick Tree) used for efficient prefix frequency queries. The algorithm also relies on prefix sums and coordinate compression to handle negative or large prefix values.
What is the time complexity of Count Subarrays With Majority Element II?
The optimal solution runs in O(n log n) time using prefix sums and a Binary Indexed Tree to count valid prefix pairs. Simpler approaches such as checking every subarray take O(n^2) or O(n^3), which become too slow for large arrays.

Ready to solve this problem?

Practice Count Subarrays With Majority Element II with our built-in code editor and test cases.

Practice on FleetCode