15% off all plans & roadmaps Use code
See plansLeetCode 907 · Solution & editorial
Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
Sum of Subarray Minimums is a Stack Patterns problem, in the Monotonic Stack subpattern. The pattern covers parentheses matching, monotonic stack, histogram, and expression evaluation
Master monotonic stack for next greater element, daily temperatures, and stock span problems.
The reference solution runs in O(n) time and O(n) space.
Sum of Subarray Minimums has been reported in interviews at Google, Dunzo, Microsoft, VMware.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Sum of Subarray Minimums is a Stack Patterns problem, in the Monotonic Stack subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.