#3737
Medium Algorithms Count subarrays with majority element i
Array Hash Table Divide and Conquer Segment Tree Merge Sort Counting Prefix Sum
65.2% acceptance
Feb 24, 2026
48
4
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn count_majority_subarrays(nums: Vec<i32>, target: i32) -> i32 {
let n = nums.len();
let mut count = 0i32;
for l in 0..n {
let mut target_cnt = 0;
let mut total = 0;
for r in l..n {
total += 1;
if nums[r] == target { target_cnt += 1; }
if target_cnt * 2 > total { count += 1; }
}
}
count
}
}