#2962
Count Subarrays Where Max Element Appears at Least K Times
MediumArraySliding WindowSliding WindowTwo Pointers
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)
The optimal approach uses a sliding window technique to efficiently count valid subarrays. We maintain a window that expands and contracts based on the occurrences of the maximum element.
⚙️
Algorithm
4 steps- 1Step 1: Initialize pointers for the sliding window and a counter for occurrences of the current maximum element.
- 2Step 2: Expand the right pointer to include new elements and update the maximum and its frequency.
- 3Step 3: If the maximum appears at least k times, count the valid subarrays ending at the right pointer.
- 4Step 4: Move the left pointer to shrink the window while maintaining the condition.
solution.py18 lines
1def countSubarrays(nums, k):
2 count = 0
3 left = 0
4 max_elem = -1
5 freq = 0
6 n = len(nums)
7 for right in range(n):
8 if nums[right] > max_elem:
9 max_elem = nums[right]
10 freq = 1
11 elif nums[right] == max_elem:
12 freq += 1
13 while freq >= k:
14 count += n - right
15 if nums[left] == max_elem:
16 freq -= 1
17 left += 1
18 return countℹ
Complexity note: The time complexity is O(n) because each element is processed at most twice (once when expanding and once when contracting the window). The space complexity is O(1) since we only use a few extra variables.
- 1The maximum element must be tracked efficiently to avoid redundant calculations.
- 2Using a sliding window allows us to dynamically adjust the subarray and count valid configurations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.