#3737
Count Subarrays With Majority Element I
MediumArrayHash TableDivide and ConquerSegment TreeMerge SortCountingPrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Initialize pointers and a count of target occurrences.
- 2Step 2: Expand the right pointer to include elements until the target count exceeds half the window size.
- 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.