Skip to problem
←

Sum of Subarray Minimums

Medium 0 attempts

For every nonempty contiguous subarray of arr, find its minimum value. Return the sum of all those minimums modulo 1,000,000,007.

Count subarrays by their start and end indices. Equal-valued subarrays at different positions count separately, and overlapping subarrays also count. This asks for the sum of minimum values, not the number of subarrays.

For [2,2], the two singleton subarrays and the full subarray each contribute 2, giving 6.

Function contract

Implement sumSubarrayMins(arr).

Output: Return the sum of the minimum of every nonempty contiguous subarray, modulo 1000000007.

Example 1

Input
arr = [3,1,2,4]
Output
17

Example 2

Input
arr = [2,2]
Output
6

Explanation: There are three subarrays by index: the first [2], the second [2], and [2,2]. Each has minimum 2, so the total is 6.

Constraints
  • 1 <= arr.length <= 3 * 10^4
  • 1 <= arr[i] <= 3 * 10^4

Monotonic Stack (Contribution)

Count how many subarrays assign their minimum to each index j. Its left boundary is the nearest strictly smaller value; its right boundary is the nearest smaller-or-equal value. There are left × right choices of endpoints, contributing arr[j] × left × right.

The asymmetric comparisons are essential: when minimum values tie, this rule assigns the subarray to its rightmost minimum exactly once. Pop on greater-or-equal values to enforce that convention. A final sentinel iteration flushes the remaining stack without reading beyond the array.

Each index is pushed and popped once. Under the stated limits, contribution products are below JavaScript's maximum safe integer, so Number arithmetic is exact before taking the modulo.

javascript
function sumSubarrayMins(arr) {
  const MOD = 1e9+7, n = arr.length, stack = [];
  let sum = 0;
  for (let i = 0; i <= n; i++) {
    while (stack.length && (i===n || arr[stack[stack.length-1]] >= arr[i])) {
      const j = stack.pop();
      const left = stack.length ? j - stack[stack.length-1] : j + 1;
      const right = i - j;
      sum = (sum + arr[j] * left * right) % MOD;
    }
    stack.push(i);
  }
  return sum;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript