The Number of Valid Subarrays problem asks you to count subarrays where the minimum element is at the leftmost position. In other words, count subarrays [l..r] where arr[l] ≤ arr[i] for all i in [l..r]. This is equivalent to asking: for each starting position l, how many valid right endpoints r exist before a smaller element appears. This hard coding problem uses a monotonic stack.
Hulu and Amazon ask this because it maps directly to the "next smaller element" problem — for each l, the valid right boundary is just before the next element smaller than arr[l]. Using a monotonic stack, this is solvable in O(n). The array, monotonic stack, and stack interview pattern is the core.
Monotonic stack for next smaller element. For each index l, find nextSmaller[l] = the first index r where arr[r] < arr[l]. The count of valid subarrays starting at l = nextSmaller[l] - l. Sum all these counts. Use a monotonic increasing stack to compute all nextSmaller values in O(n).
arr=[1,4,2,5,3]. nextSmaller:
nextSmaller[l] - l (distance to next smaller, not including it).The monotonic stack for "next smaller element" is the foundation for many hard subarray counting problems. Once you have nextSmaller[l] for all l, subarray counting reduces to a simple sum. Practice computing next smaller, previous smaller, next greater, and previous greater element arrays using monotonic stacks — these four arrays serve as building blocks for dozens of hard problems at Amazon and Hulu.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Visible People in a Queue | Hard | Solve | |
| Largest Rectangle in Histogram | Hard | Solve | |
| Count Bowl Subarrays | Medium | Solve | |
| Maximal Range That Each Element Is Maximum in It | Medium | Solve | |
| Maximum of Minimum Values in All Subarrays | Medium | Solve |