Sum of Subarray Minimums

medium

Given an array arr, consider every contiguous subarray and take its minimum element. Return the sum of all those minimums. Because the answer can be large, return it modulo 10^9 + 7.

Hints

Enumerating subarrays is O(n^2). Instead, ask: for each element, how many subarrays is it the minimum of?
That count is (distance to previous smaller) x (distance to next smaller).
Use strict on one side and non-strict on the other to count equal minimums exactly once.

Common doubts

Each subarray has exactly one minimum, so summing (value x number-of-subarrays-it-minimizes) over elements equals the total — and each count is O(1) with the boundaries.
Without the asymmetry, a run of equal minimums would credit the same subarray to multiple elements (or none). Strict-on-one-side attributes each subarray to a single index.
value x left x right can exceed 32 bits; accumulate in 64-bit (or BigInt) and take the result modulo 1e9+7.

Interview follow-ups

Mirror it — use previous/next greater boundaries instead of smaller.
Range = max - min per subarray, so sum of ranges = (sum of maximums) - (sum of minimums), each computed this way.

Fun facts

  • The 'each element contributes value x span-left x span-right' identity is the backbone of many subarray-aggregate problems.
  • The strict/non-strict tie-break is a subtle but classic source of off-by-one bugs — worth internalizing once.

Asked at

AmazonGoogleMeta
Frequently Sometimes Occasionally
Example 1
Input: arr = [3,1,2,4]
Output: 17
Subarray minimums are 3,1,2,4,1,1,2,1,1,2; their sum is 17.
Example 2
Input: arr = [11,81,94,43,3]
Output: 444
Summing the minimum of all 15 subarrays gives 444.
Constraints

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

Solve this problem →