#3739

Count Subarrays With Majority Element II

Hard
ArrayHash TableDivide and ConquerSegment TreeMerge SortPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Transform the array to +1/-1 based on the target, then use prefix sums to count valid subarrays efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert nums to arr where arr[i] = 1 if nums[i] == target else -1.
  2. 2Step 2: Build prefix sums and count occurrences of each prefix sum in a hashmap.
  3. 3Step 3: For each prefix sum, check how many times it has been seen before to find valid subarrays.
solution.py10 lines
1def countMajoritySubarrays(nums, target):
2    arr = [1 if x == target else -1 for x in nums]
3    prefix_count = {0: 1}
4    count, prefix_sum = 0, 0
5    for num in arr:
6        prefix_sum += num
7        if prefix_sum > 0:
8            count += prefix_count.get(prefix_sum - 1, 0)
9        prefix_count[prefix_sum] = prefix_count.get(prefix_sum, 0) + 1
10    return count

Complexity note: We traverse the array once and use a hashmap for prefix sums, leading to linear time complexity.

  • 1Majority element must appear more than half the time in subarrays.
  • 2Transforming the problem can simplify counting occurrences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.