Sum of Subarray Minimums - Problem

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 10^9 + 7.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: arr = [3,1,2,4]
Output: 17
💡 Note: Subarrays: [3]→3, [1]→1, [2]→2, [4]→4, [3,1]→1, [1,2]→1, [2,4]→2, [3,1,2]→1, [1,2,4]→1, [3,1,2,4]→1. Sum = 3+1+2+4+1+1+2+1+1+1 = 17
Example 2 — Small Array
$ Input: arr = [11,81,94,43,3]
Output: 444
💡 Note: All 15 possible subarrays are considered, with their minimum values summed up to get 444
Example 3 — Single Element
$ Input: arr = [5]
Output: 5
💡 Note: Only one subarray [5] with minimum 5

Constraints

  • 1 ≤ arr.length ≤ 3 × 104
  • 1 ≤ arr[i] ≤ 3 × 104

Visualization

Tap to expand
Sum of Subarray Minimums INPUT arr = [3, 1, 2, 4] 3 i=0 1 i=1 2 i=2 4 i=3 All Subarrays: [3] min=3 [3,1] min=1 [3,1,2] min=1 [3,1,2,4] min=1 [1] min=1 [1,2] min=1 [1,2,4] min=1 [2] min=2 [2,4] min=2 [4] min=4 ALGORITHM STEPS 1 Monotonic Stack Find prev/next smaller elements 2 Calculate Contribution arr[i] * left * right 3 Sum All Contributions Add each element's total 4 Apply Modulo result % (10^9 + 7) Contribution Calculation i=0: 3*(1)*(1) = 3 i=1: 1*(2)*(3) = 6 i=2: 2*(1)*(2) = 4 i=3: 4*(1)*(1) = 4 Total: 3+6+4+4 = 17 FINAL RESULT Sum of all subarray minimums: 17 OK Verification: 3+1+1+1+1+1+1+2+2+4 = 17 Complexity Time: O(n) Space: O(n) Key Insight: Each element arr[i] is the minimum for subarrays determined by its "span" - the range where it remains minimum. Use monotonic stack to find previous and next smaller elements, then contribution = arr[i] * left_count * right_count. TutorialsPoint - Sum of Subarray Minimums | Optimal Solution (Monotonic Stack)
Asked in
Google 45 Amazon 38 Microsoft 32
89.0K Views
Medium Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen