LeetCode #907 Medium

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.
Constraints
  • 1 <= arr.length <= 3 * 10^4
  • 1 <= arr[i] <= 3 * 10^4
monotonic-stackarraycontribution
Open on LeetCode ↗
02

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.

How to spot this pattern

"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).

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def sumSubarrayMins(self, arr):
▶3 MOD = 10**9 + 7
▶4 n = len(arr)
▶5 stack = []
▶6 total = 0
▶7 for i in range(n + 1):
▶8 while stack and (i == n or arr[stack[-1]] >= arr[i]):
▶9 mid = stack.pop()
▶10 left = stack[-1] if stack else -1
▶11 total += arr[mid] * (mid - left) * (i - mid)
▶12 if i < n:
▶13 stack.append(i)
▶14 return total % MOD
3i0112243endstack3addsvalue×left ends×right ends=addstotal0push 3: its right edge is not known yet
i0
stack[3]values, bottom to top
The stack is empty, so 3 goes straight in. Its right edge is not known yet: it waits until a value that is not larger arrives.
301i12243endstackemptyadds3value×1left ends×1right ends=3addstotal33 is the minimum of 1 × 1 subarrays → adds 3
mid0value 3
left-1nothing smaller on the left
total3
Pop 3: 1 at index 1 is smaller. Nothing smaller is left in the stack, so its stretch reaches index 0. So 3 is the minimum of every subarray inside the green bracket: 1 left end × 1 right end, adding 3 × 1 = 3.
301i12243endstack1addsvalue×left ends×right ends=addstotal3push 1: its right edge is not known yet
i1
stack[1]values, bottom to top
The stack is empty, so 1 goes straight in. Its right edge is not known yet: it waits until a value that is not larger arrives.
30112i243endstack12addsvalue×left ends×right ends=addstotal3push 2: its right edge is not known yet
i2
stack[1, 2]values, bottom to top
Everything under 2 in the stack is smaller, so the stack stays increasing. Its right edge is not known yet: it waits until a value that is not larger arrives.
3011224i3endstack124addsvalue×left ends×right ends=addstotal3push 4: its right edge is not known yet
i3
stack[1, 2, 4]values, bottom to top
Everything under 4 in the stack is smaller, so the stack stays increasing. Its right edge is not known yet: it waits until a value that is not larger arrives.
30112243endistack12adds4value×1left ends×1right ends=4addstotal74 is the minimum of 1 × 1 subarrays → adds 4
mid3value 4
left2value 2
total7
Pop 4: the array ends after index 3. The value under it in the stack, 2 at index 2, is smaller and stops its stretch on the left. So 4 is the minimum of every subarray inside the green bracket: 1 left end × 1 right end, adding 4 × 1 = 4.
30112243endistack1adds2value×1left ends×2right ends=4addstotal112 is the minimum of 1 × 2 subarrays → adds 4
mid2value 2
left1value 1
total11
Pop 2: the array ends after index 3. The value under it in the stack, 1 at index 1, is smaller and stops its stretch on the left. So 2 is the minimum of every subarray inside the green bracket: 1 left end × 2 right ends, adding 2 × 2 = 4.
30112243endistackemptyadds1value×2left ends×3right ends=6addstotal171 is the minimum of 2 × 3 subarrays → adds 6
mid1value 1
left-1nothing smaller on the left
total17
Pop 1: the array ends after index 3. Nothing smaller is left in the stack, so its stretch reaches index 0. So 1 is the minimum of every subarray inside the green bracket: 2 left ends × 3 right ends, adding 1 × 6 = 6.
30112243endstackemptyaddsvalue×left ends×right ends=addstotal17every value counted → answer 17
total17
result17mod 10^9 + 7
Each index was pushed once and popped once, and each pop added that value times the number of subarrays it is the minimum of. Those counts cover all 10 subarrays exactly once, so the sum is 17.
05

Common pitfalls

Using the same tie rule on both sides

✗ Wrong
left edge:  nearest value < arr[i]
right edge: nearest value < arr[i]
✓ Right
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

✗ Wrong
left = stack[-1] if stack else 0
✓ Right
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

✗ Wrong
int total = 0;
✓ Right
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.

06

Complexity

Time
O(n)
Space
O(n)
Each index is pushed once and popped once, and the extra round at i == n empties the stack. In a strictly increasing array nothing pops until that last round, so the stack can hold all n indices.
07

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).