sagelearnai

Sum of Subarray Minimums

Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #907

Return the sum of min(b) over every contiguous subarray b of arr, modulo 10⁹ + 7.

Examples

text
[3, 1, 2, 4]          →  17
[11, 81, 94, 43, 3]   →  444

Hints

  1. Instead of enumerating subarrays, ask for how many subarrays each element is the minimum.
  2. That count is (distance to the previous smaller element) × (distance to the next smaller-or-equal element).
  3. Use strict and non-strict comparisons on the two sides so duplicates aren't double-counted.

Approach

For each index i, let left[i] be the number of choices for the subarray start (i − previous index with a strictly smaller value) and right[i] the number of choices for the end (next index with a smaller or equal value − i). Element i is the minimum of left·right subarrays, so the answer is Σ arr[i]·left[i]·right[i]. Both arrays come from monotonic stacks in O(n). (In a single pass: when an index is popped, its contribution is known.)

Complexity

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

Python solution
def sumSubarrayMins(arr):
    MOD = 10**9 + 7
    n = len(arr)
    ans, st = 0, []                 # increasing stack of indices
    for i in range(n + 1):
        cur = arr[i] if i < n else 0  # sentinel flushes the stack
        while st and arr[st[-1]] >= cur:
            j = st.pop()
            left = j - (st[-1] if st else -1)
            right = i - j
            ans += arr[j] * left * right
        st.append(i)
    return ans % MOD
JavaScript solution
function sumSubarrayMins(arr) {
  const MOD = 1000000007n, n = arr.length, st = []; let ans = 0n;
  for (let i = 0; i <= n; i++) {
    const cur = i < n ? arr[i] : 0;
    while (st.length && arr[st[st.length - 1]] >= cur) {
      const j = st.pop(), left = j - (st.length ? st[st.length - 1] : -1), right = i - j;
      ans += BigInt(arr[j]) * BigInt(left) * BigInt(right);
    }
    st.push(i);
  }
  return Number(ans % MOD);
}