Sum of Subarray Minimums (LeetCode 907): Solution and Explanation

Medium
Array
Dynamic programming
Stack
Monotonic stack

Add up the minimum of every contiguous subarray, modulo 10^9 + 7. For [3,1,2,4] the ten subarrays have minimums summing to 17.

Intuition

There are O(n^2) subarrays, so listing them is too slow. Flip the question: for each index, how many subarrays have this value as their minimum?

arr[mid] is the minimum of a subarray exactly when the subarray stays between the nearest smaller value on the left and the nearest smaller value on the right. If those walls are at left and right, a subarray can start at any of the (mid - left) positions and end at any of the (right - mid) positions, so arr[mid] contributes arr[mid] × (mid - left) × (right - mid).

A stack whose values rise from bottom to top finds both walls at once. When a value pops index mid, that value is mid's right wall, and the index now below mid on the stack is its left wall.

Approach: Monotonic stack with contribution counting

  1. Keep a stack of indexes with rising values and a running total.
  2. Scan i from 0 to n. Use cur = arr[i], or a sentinel 0 when i = n so every remaining index gets popped.
  3. While the top value is >= cur, pop it as mid. Let left be the new top, or -1 if the stack is empty. Add arr[mid] × (mid - left) × (i - mid) to the total, modulo 10^9 + 7.
  4. Push i.
  5. Return the total.

Step-by-step example

arr = [3,1,2,4]
  1. i = 0: push 0. Stack [0].
  2. i = 1, cur = 1: pop 0 (value 3). left = -1, so 1 × 1 = 1 subarray, add 3. Push 1. Total 3.
  3. i = 2 and i = 3: values 2 and 4 are larger than the top, so push both. Stack [1,2,3].
  4. i = 4 (sentinel 0): pop 3 (value 4): 1 × 1 subarray, add 4. Pop 2 (value 2): 1 × 2 subarrays, add 4. Pop 1 (value 1): 2 × 3 subarrays, add 6.
  5. Total 3 + 4 + 4 + 6 = 17.

Code: Python, Java, C++

1class Solution:
2    def sumSubarrayMins(self, arr: List[int]) -> int:
3        MOD = 10**9 + 7
4        n = len(arr)
5        stack = []
6        total = 0
7        for i in range(n + 1):
8            cur = arr[i] if i < n else 0
9            while stack and arr[stack[-1]] >= cur:
10                mid = stack.pop()
11                left = stack[-1] if stack else -1
12                total = (total + arr[mid] * (mid - left) * (i - mid)) % MOD
13            stack.append(i)
14        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is pushed once and popped once, and every pop does constant work.

Space

O(n)

The stack can hold every index when the array is increasing.

Other approaches

Previous and next smaller arrays (time O(n), space O(n))

Run two separate monotonic stack passes to build prevLess[i] (strictly smaller) and nextLessOrEqual[i], then sum arr[i] × (i - prevLess[i]) × (nextLessOrEqual[i] - i). Same idea, three passes instead of one.

DP on the stack (time O(n), space O(n))

Let dp[i] be the sum of minimums of subarrays ending at i. With j the previous smaller index, dp[i] = dp[j] + arr[i] × (i - j). The answer is the sum of dp.

Brute force (time O(n^2), space O(1))

For each start, extend the end and keep a running minimum. Simple, but O(n^2) is too slow for n = 3 × 10^4.

Common mistakes

  • Double counting equal values. Break ties on one side only: here a later value pops on >=, so the right wall is smaller-or-equal and the left wall is strictly smaller.
  • Forgetting the leftover stack. Without the sentinel 0 at i = n, indexes still on the stack never get counted.
  • Overflow. arr[mid] × (mid - left) × (i - mid) can reach about 2.7 × 10^13, so use a 64-bit type before taking the modulo.

Frequently asked questions

Why does the popping index count as the right wall?

Everything between mid and i was pushed after mid and was larger, otherwise mid would already have been popped. So i is the first index to the right whose value is <= arr[mid].

Why is the index below mid the left wall?

Values on the stack rise from bottom to top, and anything between them was popped by a smaller or equal value. So the index below mid is the nearest one to the left with a strictly smaller value.

How does this relate to Largest Rectangle in Histogram?

It is the same stack and the same walls. In the histogram problem you use width (right - left - 1) times height. Here you use the number of start positions times the number of end positions.