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: [3,1,2,4]3124All subarrays and their minimums:Length 1: [3]→3, [1]→1, [2]→2, [4]→4Length 2: [3,1]→1, [1,2]→1, [2,4]→2Length 3: [3,1,2]→1, [1,2,4]→1Length 4: [3,1,2,4]→1Sum of all minimums = 3+1+2+4+1+1+2+1+1+1 = 17
Understanding the Visualization
1
Input Array
Given array [3,1,2,4]
2
Find All Subarrays
Generate all contiguous subarrays and find minimum of each
3
Sum Minimums
Add all minimum values together
Key Takeaway
🎯 Key Insight: Count how many subarrays each element is minimum for instead of generating all subarrays
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