#3737

Count Subarrays With Majority Element I

Medium
ArrayHash TableDivide and ConquerSegment TreeMerge SortCountingPrefix SumHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

We can use a two-pointer technique to efficiently count valid subarrays by maintaining a count of the target and adjusting the window size dynamically.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize pointers and a count of target occurrences.
  2. 2Step 2: Expand the right pointer to include elements until the target count exceeds half the window size.
  3. 3Step 3: Count valid subarrays and adjust the left pointer to find new valid ranges.
solution.py13 lines
1def countSubarrays(nums, target):
2    count = 0
3    target_count = 0
4    left = 0
5    for right in range(len(nums)):
6        if nums[right] == target:
7            target_count += 1
8        while target_count > (right - left + 1) // 2:
9            count += (right - left + 1) - (right - left - target_count + 1)
10            if nums[left] == target:
11                target_count -= 1
12            left += 1
13    return count

Complexity note: We only traverse the array once, leading to O(n) time complexity.

  • 1Majority element must appear more than half the time in subarrays.
  • 2Efficient counting can reduce time complexity significantly.

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