Skip to main content

Count Subarrays With Majority Element I - Solution & Explanation

MediumArrayHash TableDivide and ConquerSegment Tree7 min readAsked at: Amazon, Microsoft, Meta +2
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 <= 1000
  • 1 <= nums[i] <= 10​​​​​​​9
  • 1 <= target <= 109

Approach Overview

Problem Overview: You are given an array and must count how many subarrays contain a majority element, meaning one value appears strictly more than half of the subarray length. The challenge is efficiently checking the majority condition across all possible subarrays.

Approach 1: Brute Force Enumeration (O(n^3) time, O(1) space)

The most direct strategy enumerates every subarray using two nested loops and then checks whether a majority element exists inside it. For each subarray [i, j], count frequencies of elements and verify whether any value occurs more than (j - i + 1) / 2 times. This requires scanning the subarray again to compute counts, resulting in O(n^3) time. It is straightforward and useful for understanding the majority definition but becomes impractical for large arrays.

Approach 2: Optimized Enumeration with Frequency Map (O(n^2) time, O(n) space)

A better solution still enumerates all subarrays but avoids recomputing frequencies from scratch. Fix the starting index i, then extend the right boundary j one step at a time. Maintain a running frequency map using a hash table and track the current maximum frequency. For each extension, update the count of nums[j], update the max frequency, and check whether maxFreq * 2 > (j - i + 1). This converts the inner work from scanning the entire subarray to constant-time updates, reducing total complexity to O(n^2). This approach is practical for medium input sizes and commonly appears in interview-style enumeration problems.

Approach 3: Prefix Balance Transformation (Conceptual Optimization)

For deeper optimization, the majority condition can be transformed using prefix balances. For a chosen candidate value, convert the array into +1 (candidate) and -1 (others). A subarray has that candidate as majority if its transformed sum is positive. Using techniques from prefix sum and counting valid prefix differences (sometimes with divide and conquer or merge-based counting), you can count qualifying segments more efficiently for each candidate. While more complex, this idea connects majority detection with classic prefix comparison problems.

Recommended for interviews: The optimized enumeration approach is the most practical answer. It demonstrates understanding of subarray enumeration, incremental frequency updates, and hash-based counting. Mentioning the brute force approach shows baseline reasoning, while the optimized O(n^2) solution proves you can reduce redundant work.

Solution

We can enumerate all subarrays and use a hash table to record the occurrence count of each element in the subarray, then determine whether the target element is the majority element of that subarray.

Specifically, we enumerate the starting position i of the subarray in the range [0, n-1], then enumerate the ending position j in the range [i, n-1]. For each subarray nums[i..j], we update the hash table cnt. If cnt[target] > \frac{(j-i+1)}{2}, we increment the answer by 1.

The time complexity is O(n^2), 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 EnumerationO(n^3)O(1)Good for understanding the majority condition or very small arrays
Enumeration with Frequency MapO(n^2)O(n)General solution for medium constraints and typical interview answers
Prefix Balance / Counting TechniqueO(n log n) or better depending on implementationO(n)Advanced optimization using prefix sums and divide-and-conquer counting

Video Solution

Count Subarrays With Majority Element I šŸ”„ Leetcode 3737 | Medium Problem • Study Placement • 2,881 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Subarrays With Majority Element I easy or hard?
The problem is typically rated Medium because the brute force idea is simple but optimizing the counting requires careful tracking of frequencies or applying prefix-sum transformations. Recognizing the majority condition inside dynamically growing subarrays is the key challenge.
Count Subarrays With Majority Element I Python/Java solution
Most implementations iterate over all starting indices and maintain a frequency dictionary (Python) or HashMap (Java) while expanding the subarray. Each update checks whether the maximum frequency exceeds half the current length, allowing valid subarrays to be counted in O(n^2) time.
How to solve Count Subarrays With Majority Element I in O(n)?
A strict O(n) solution is generally not feasible for the unrestricted version because every possible subarray must be considered. However, transforming the array using prefix balances for candidate elements and applying prefix-sum counting can reduce complexity to around O(n log n) in more advanced implementations.
What is the best approach for Count Subarrays With Majority Element I?
The practical solution uses enumeration with a running frequency map. Fix a starting index, expand the subarray to the right, update element frequencies in a hash table, and track the maximum frequency. A subarray has a majority element when maxFreq * 2 > length. This approach runs in O(n^2) time and O(n) space.
Is Count Subarrays With Majority Element I asked at Google/Amazon/Meta?
Majority element and subarray counting patterns appear frequently in interviews at companies like Google, Amazon, and Meta. Variations often combine array traversal, hash tables, and prefix sum reasoning to detect dominant elements in ranges.
What data structure is used in Count Subarrays With Majority Element I?
The common solution uses a hash table to maintain frequencies of elements within the current subarray while enumerating ranges. Some optimized strategies also rely on prefix sum arrays and counting techniques derived from divide-and-conquer algorithms.
What is the time complexity of Count Subarrays With Majority Element I?
The optimized enumeration approach runs in O(n^2) time because each starting index expands through the rest of the array once while updating counts in constant time. Space complexity is O(n) for the frequency map. A naive brute force solution can take O(n^3).

Ready to solve this problem?

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

Practice on FleetCode