Sum of Subarray Minimums
Medium
Topics
Given an array nums, find the minimum of every contiguous subarray and return the sum of all those minimums.
The answer can be large, so return it modulo 10^9 + 7.
Example 1
Input: nums = [3,1,2,4] Output: 17 Explanation: The minimums are 3,1,2,4 then 1,1,2 then 1,1 then 1, summing to 17.
Example 2
Input: nums = [11,81,94,43,3] Output: 444 Explanation: A larger case; 3 is the minimum of every subarray that reaches the end.
Example 3
Input: nums = [5] Output: 5 Explanation: One subarray, whose minimum is the only element.
Constraints
- 1 <= nums.length <= 3 * 10^4
- 1 <= nums[i] <= 3 * 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Enumerating the subarrays is quadratic at best and the limit rules it out. The way in is to stop asking "what is the minimum of this subarray" and start asking the inverted question: for each element, how many subarrays have it as their minimum? Multiply that count by the value, sum over all elements, and you are done.
That count is determined by how far the element can extend in each direction before meeting something smaller. If nums[i] can reach left positions to its left and right positions to its right without meeting a smaller value, then it is the minimum of exactly left * right subarrays — any start in its left reach paired with any end in its right reach.
Equal values are where this goes wrong if you are not careful. If both of two equal elements may claim a subarray, that subarray is counted twice. The fix is to break the tie by convention: let one direction stop at values strictly smaller and the other stop at values smaller or equal. Then each subarray belongs to exactly one of them.
Finding those reaches for every element is the one remaining piece, and it is the standard previous-smaller and next-smaller computation — each element is pushed and popped once while scanning.
Approach
- For each index, find the distance to the previous element strictly smaller than it, and the distance to the next element smaller than or equal to it. The asymmetry is what prevents double counting on equal values.
- Treat a missing boundary as being just outside the array, so an element that is the smallest overall reaches the whole way.
- The number of subarrays minimised by index
iisleft * right, whereleftis the number of valid starting positions andrightthe number of valid ending positions. - Accumulate
nums[i] * left * right, taking the modulus as you go. - Both reaches can be computed in one scan each with a stack that holds indices of values still looking for their boundary.
Walkthrough
nums = [3,1,2,4]
for each element: how far left and right can it dominate?
i=0, value 3
left: nothing smaller before it, reach 1 start
right: nums[1] = 1 is smaller, so it stops, reach 1 end
subarrays minimised: 1 * 1 = 1 -> [3]
contribution 3 * 1 = 3
i=1, value 1
left: nothing smaller before, reach 2 starts (index 0 or 1)
right: nothing smaller after, reach 3 ends (index 1, 2 or 3)
subarrays: 2 * 3 = 6
contribution 1 * 6 = 6
i=2, value 2
left: nums[1] = 1 smaller, reach 1 start
right: nums[3] = 4 not smaller, end of array, reach 2 ends
subarrays: 1 * 2 = 2 -> [2], [2,4]
contribution 2 * 2 = 4
i=3, value 4
left: nums[2] = 2 smaller, reach 1
right: end of array, reach 1
subarrays: 1 -> [4]
contribution 4
total 3 + 6 + 4 + 4 = 17
check: 1 + 6 + 2 + 1 = 10 subarrays, and there are
4*5/2 = 10 of them, so every subarray was counted once.Complexity
- Time — O(n): each index is pushed and popped at most once in each of the two scans.
- Space — O(n): the two boundary arrays and the stack.
Common Pitfalls
- Using the same strictness on both sides, which double counts every subarray whose minimum occurs more than once.
- Enumerating subarrays. Correct and far too slow at thirty thousand elements.
- Taking the modulus only at the end. The product
value * left * rightcan overflow a 32-bit integer well before the sum does. - Treating a missing boundary as the array edge rather than one past it, which loses a position from the reach.
- Computing the reaches as counts rather than as indices and then subtracting in the wrong direction.
Full Solution — all languages
class Solution:
def sumSubarrayMins(self, nums):
MOD = 10 ** 9 + 7
n = len(nums)
# prev[i]: index of the previous STRICTLY smaller value, else -1
# next[i]: index of the next SMALLER OR EQUAL value, else n
# The strict/non-strict split is what stops equal values both
# claiming the same subarray.
prev, nxt = [-1] * n, [n] * n
stack = []
for i in range(n):
while stack and nums[stack[-1]] >= nums[i]:
stack.pop()
prev[i] = stack[-1] if stack else -1
stack.append(i)
stack = []
for i in range(n - 1, -1, -1):
while stack and nums[stack[-1]] > nums[i]:
stack.pop()
nxt[i] = stack[-1] if stack else n
stack.append(i)
total = 0
for i in range(n):
left = i - prev[i] # choices of start
right = nxt[i] - i # choices of end
total = (total + nums[i] * left * right) % MOD
return totalimport java.util.*;
class Solution {
public int sumSubarrayMins(int[] nums) {
final long MOD = 1000000007L;
int n = nums.length;
int[] prev = new int[n], nxt = new int[n];
Arrays.fill(prev, -1);
Arrays.fill(nxt, n);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) stack.pop();
prev[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[stack.peek()] > nums[i]) stack.pop();
nxt[i] = stack.isEmpty() ? n : stack.peek();
stack.push(i);
}
long total = 0;
for (int i = 0; i < n; i++) {
long left = i - prev[i], right = nxt[i] - i;
total = (total + (long) nums[i] * left % MOD * right) % MOD;
}
return (int) total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int sumSubarrayMins(vector<int>& nums) {
const long long MOD = 1000000007LL;
int n = (int)nums.size();
vector<int> prev(n, -1), nxt(n, n);
vector<int> stack;
for (int i = 0; i < n; i++) {
while (!stack.empty() && nums[stack.back()] >= nums[i]) stack.pop_back();
prev[i] = stack.empty() ? -1 : stack.back();
stack.push_back(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.empty() && nums[stack.back()] > nums[i]) stack.pop_back();
nxt[i] = stack.empty() ? n : stack.back();
stack.push_back(i);
}
long long total = 0;
for (int i = 0; i < n; i++) {
long long left = i - prev[i], right = nxt[i] - i;
total = (total + (long long)nums[i] % MOD * left % MOD * right) % MOD;
}
return (int)total;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var sumSubarrayMins = function(nums) {
const MOD = 1000000007n;
const n = nums.length;
const prev = new Array(n).fill(-1), nxt = new Array(n).fill(n);
let stack = [];
for (let i = 0; i < n; i++) {
while (stack.length && nums[stack[stack.length - 1]] >= nums[i]) stack.pop();
prev[i] = stack.length ? stack[stack.length - 1] : -1;
stack.push(i);
}
stack = [];
for (let i = n - 1; i >= 0; i--) {
while (stack.length && nums[stack[stack.length - 1]] > nums[i]) stack.pop();
nxt[i] = stack.length ? stack[stack.length - 1] : n;
stack.push(i);
}
// The product can exceed 2^53, so accumulate in BigInt.
let total = 0n;
for (let i = 0; i < n; i++) {
const left = BigInt(i - prev[i]), right = BigInt(nxt[i] - i);
total = (total + BigInt(nums[i]) * left * right) % MOD;
}
return Number(total);
};