907. Sum of Subarray Minimums
Asked at 14Amazon51Google46Microsoft40Bloomberg37Meta28ZS Associates88Avito83Sprinklr72Cashfree66Flipkart59Morgan Stanley54Accenture44Infosys30TikTok26
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
assert Solution().sumSubarrayMins([3, 1, 2, 4]) == 17
assert Solution().sumSubarrayMins([11, 81, 94, 43, 3]) == 444
class Solution {
public int sumSubarrayMins(int[] arr) {
int n = arr.length;
long MOD = 1_000_000_007L, res = 0;
int[] left = new int[n], right = new int[n];
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] > arr[i]) st.pop();
left[i] = i - (st.isEmpty() ? -1 : st.peek());
st.push(i);
}
st.clear();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && arr[st.peek()] >= arr[i]) st.pop();
right[i] = (st.isEmpty() ? n : st.peek()) - i;
st.push(i);
}
for (int i = 0; i < n; i++) res = (res + (long) arr[i] * left[i] % MOD * right[i]) % MOD;
return (int) res;
}
}
func sumSubarrayMins(arr []int) int {
const MOD = 1_000_000_007
n := len(arr)
left, right, st := make([]int, n), make([]int, n), []int{}
for i := 0; i < n; i++ { // left[i]: choices of start where arr[i] is the min
for len(st) > 0 && arr[st[len(st)-1]] > arr[i] {
st = st[:len(st)-1]
}
left[i] = i + 1
if len(st) > 0 {
left[i] = i - st[len(st)-1]
}
st = append(st, i)
}
st = st[:0]
for i := n - 1; i >= 0; i-- { // >= on this side so equal values are counted once
for len(st) > 0 && arr[st[len(st)-1]] >= arr[i] {
st = st[:len(st)-1]
}
right[i] = n - i
if len(st) > 0 {
right[i] = st[len(st)-1] - i
}
st = append(st, i)
}
sum := 0
for i, a := range arr {
sum = (sum + a*left[i]*right[i]) % MOD
}
return sum
}