DSA Stacks

Number of Valid Subarrays

For each index, count subarrays ending at it where nums[i] is the leftmost minimum — monotonic stack.

Hard
Time O(n) Space O(n)
LeetCode
3 min read
monotonic-stack

Problem#

Given an integer array nums, count the number of non-empty subarrays where the leftmost element is the smallest in that subarray.

Examples#

  • nums = [1,4,2,5,3]11
  • nums = [3,2,1]3
  • nums = [2,2,2]6

Constraints#

  • 1 <= nums.length <= 5 * 10^4, 0 <= nums[i] <= 10^5.

Approach#

For each index i, count subarrays where nums[i] is the leftmost smallest. That’s (next strictly smaller index to the right of i) - i. Compute next-smaller indices with a monotonic stack.

Solution#

Number of Valid Subarrays
class Solution {
public:
int validSubarrays(vector<int>& nums) {
int n = nums.size();
long long ans = 0;
stack<int> st;
for (int i = 0; i < n; ++i) {
while (!st.empty() && nums[st.top()] > nums[i]) {
int idx = st.top(); st.pop();
ans += i - idx;
}
st.push(i);
}
while (!st.empty()) {
int idx = st.top(); st.pop();
ans += n - idx;
}
return (int)ans;
}
};

Editorial#

A subarray [i..j] is valid iff nums[i] <= nums[k] for all i <= k <= j. For a fixed i, the maximum valid j is one less than the first index to the right with nums[k] < nums[i]. Summing those widths across i gives the answer.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.