#3113
Find the Number of Subarrays Where Boundary Elements Are Maximum
HardArrayBinary SearchStackMonotonic StackMonotonic StackTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a monotonic stack to efficiently find the nearest smaller elements to the left and right of each element. This allows us to calculate valid subarrays in linear time.
⚙️
Algorithm
7 steps- 1Step 1: Initialize a stack to keep track of indices and a counter for valid subarrays.
- 2Step 2: Create an array to store the nearest smaller element indices to the left for each element.
- 3Step 3: Traverse the array and fill the left nearest smaller indices using the stack.
- 4Step 4: Create another array for the nearest smaller element indices to the right.
- 5Step 5: Traverse the array in reverse to fill the right nearest smaller indices using the stack.
- 6Step 6: For each element, calculate the number of valid subarrays using the left and right indices.
- 7Step 7: Return the total count of valid subarrays.
solution.py20 lines
1def countSubarrays(nums):
2 n = len(nums)
3 left = [0] * n
4 right = [0] * n
5 stack = []
6 for i in range(n):
7 while stack and nums[stack[-1]] < nums[i]:
8 stack.pop()
9 left[i] = stack[-1] if stack else -1
10 stack.append(i)
11 stack = []
12 for i in range(n-1, -1, -1):
13 while stack and nums[stack[-1]] <= nums[i]:
14 stack.pop()
15 right[i] = stack[-1] if stack else n
16 stack.append(i)
17 count = 0
18 for i in range(n):
19 count += (i - left[i]) * (right[i] - i)
20 return countℹ
Complexity note: The time complexity is O(n) because we traverse the array a constant number of times, and the space complexity is O(n) due to the storage of left and right indices.
- 1Using a monotonic stack can significantly reduce time complexity.
- 2Understanding boundaries of subarrays is crucial for counting valid ones.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.