Sum of Subarray Minimums
Sum of Subarray Minimums is LeetCode 907 (Medium). Given an integer array arr, take every contiguous subarray, find its smallest element, and return the sum of all those minimums modulo 10^9 + 7.
- An array of length n has n(n + 1)/2 subarrays. With n up to 30,000 that is about 450 million, so visiting them one by one is too slow and the target is O(n).
- Every value is between 1 and 30,000.
- 1 <= arr.length <= 3 * 10^4
- 1 <= arr[i] <= 3 * 10^4
Intuition
Instead of finding the minimum of each subarray, ask of each element: in how many subarrays is it the minimum? Its share of the answer is its value times that count.
arr[i] is the minimum of a subarray when the subarray contains index i and nothing smaller. That stretch stops just before the nearest smaller value on each side. With L choices for the left end and R choices for the right end, arr[i] is the minimum of L × R subarrays.
A stack kept in increasing order finds both edges at once. When arr[i] pops an element, i is that element's right edge, and the index just below it in the stack is its left edge.
"Sum something over all subarrays" with a min or max inside is a job for the contribution technique: count, for each element, the subarrays where it is the answer. Nearest smaller or larger values on both sides give that count, and a monotonic stack finds them in O(n).
Approach
Before reading on, take [3, 1, 2, 4] and count by hand how many subarrays have 1 as their minimum. Which two positions limit that count? Aim for O(n) time.
Keep a stack of indices with increasing values
Scan i from 0 to n. The stack holds indices whose values increase from bottom to top. These are the elements that have not yet met a value on their right that is smaller or equal.
Pop when a smaller or equal value arrives
While the top value is >= arr[i], pop it as mid. arr[i] is the first value to its right that is not larger, so i is the right edge. At i == n every index still on the stack is popped, as if a value smaller than all of them arrived.
Read the left edge from the stack
After popping mid, the new top is the nearest index to its left with a strictly smaller value, or −1 if the stack is empty. So mid is the minimum of (mid - left) × (i - mid) subarrays: that many left ends times that many right ends.
Add the contribution, then push
Add arr[mid] × (mid - left) × (i - mid) to the total, and push i once nothing larger or equal is left above it. Return the total modulo 10^9 + 7. When two minimums are equal, the subarray is counted once, under the one further right.
Code in Python, C++ and Java
Common pitfalls
Using the same tie rule on both sides
left edge: nearest value < arr[i] right edge: nearest value < arr[i]
left edge: nearest value < arr[i] right edge: nearest value <= arr[i]
This bites the common two-pass version that finds each edge in its own loop. For [2, 2], both 2s then claim the subarray [2, 2], so the result is 8 instead of 6. One side must stop at equal values so a tied subarray has exactly one owner.
Defaulting a missing left edge to 0
left = stack[-1] if stack else 0
left = stack[-1] if stack else -1
The edge is the first index outside the stretch, so with nothing smaller on the left it sits before index 0. With 0, the element at index 0 gets zero left ends: [1, 2] returns 2 instead of 4.
Adding up in a 32-bit integer
int total = 0;
long long total = 0;
Thirty thousand copies of 30,000 give a true sum near 1.35 × 10^13, far past the 2.1 × 10^9 an int holds. A 64-bit total fits it with room to spare, so the modulo can wait until the end. Python integers do not overflow.
Complexity
i == n empties the stack. In a strictly increasing array nothing pops until that last round, so the stack can hold all n indices.Sum of Subarray Minimums FAQ
Is there a dynamic programming version?
Yes. Let ends[i] be the sum of minimums over subarrays that end at i, and j the nearest index to the left with a smaller value. Then ends[i] = ends[j] + arr[i] × (i - j), because subarrays starting after j have arr[i] as their minimum and the rest behave as they did at j. Sum ends for the answer; it is still O(n) with one stack.
How does this help with Sum of Subarray Ranges?
A subarray's range is its maximum minus its minimum. Run this same count once for minimums and once with the comparison flipped for maximums, then subtract. That solves Sum of Subarray Ranges in O(n).