SDE & MLE Prep

907. Sum of Subarray Minimums

Problem

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

Example: [3,1,2,4] → 17

Constraints: n ≤ 3·10⁴.

Count, for each element, how many subarrays it is the minimum of: left[i] = distance to the previous smaller element, right[i] = distance to the next smaller-or-equal (asymmetric to avoid double-counting ties). Contribution = arr[i] · left · right.

Complexity: O(n).

class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        MOD, n = 10 ** 9 + 7, len(arr)
        left, right, st = [0] * n, [0] * n, []
        for i in range(n):
            while st and arr[st[-1]] > arr[i]:
                st.pop()
            left[i] = i - (st[-1] if st else -1)
            st.append(i)
        st = []
        for i in range(n - 1, -1, -1):
            while st and arr[st[-1]] >= arr[i]:
                st.pop()
            right[i] = (st[-1] if st else n) - i
            st.append(i)
        return sum(a * l * r for a, l, r in zip(arr, left, right)) % MOD