Number of Valid Subarrays

hard monotonic stack array stack

Problem

Given an integer array nums, return the number of non-empty subarrays in which the leftmost element of the subarray is not larger than every other element in that subarray (i.e. the first element is the minimum of the subarray).

Inputnums = [1, 4, 2, 5, 3]
Output11
Every subarray starting at index i is valid until the first strictly smaller value to its right. Those counts are 5, 1, 3, 1, 1, which sum to 11.

def valid_subarrays(nums):
    n = len(nums)
    stack = []          # indices, values increasing bottom -> top
    total = 0
    for i in range(n):
        while stack and nums[i] < nums[stack[-1]]:
            j = stack.pop()
            total += i - j
        stack.append(i)
    while stack:
        total += n - stack.pop()
    return total
function validSubarrays(nums) {
  const n = nums.length;
  const stack = [];      // indices, values increasing
  let total = 0;
  for (let i = 0; i < n; i++) {
    while (stack.length && nums[i] < nums[stack[stack.length - 1]]) {
      total += i - stack.pop();
    }
    stack.push(i);
  }
  while (stack.length) total += n - stack.pop();
  return total;
}
class Solution {
    public int validSubarrays(int[] nums) {
        int n = nums.length, total = 0;
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && nums[i] < nums[stack.peek()]) {
                total += i - stack.pop();
            }
            stack.push(i);
        }
        while (!stack.isEmpty()) total += n - stack.pop();
        return total;
    }
}
int validSubarrays(vector<int>& nums) {
    int n = (int)nums.size(), total = 0;
    vector<int> stack;     // indices, values increasing
    for (int i = 0; i < n; i++) {
        while (!stack.empty() && nums[i] < nums[stack.back()]) {
            total += i - stack.back();
            stack.pop_back();
        }
        stack.push_back(i);
    }
    while (!stack.empty()) { total += n - stack.back(); stack.pop_back(); }
    return total;
}
Time: O(n) Space: O(n)