Sum of Subarray Minimums - Problem
Sum of Subarray Minimums

Imagine you have an array of integers, and you need to find every possible contiguous subarray within it. For each subarray, you find its minimum element, then sum all these minimums together.

For example, with array [3, 1, 2, 4]:
• Subarrays of length 1: [3], [1], [2], [4] → minimums: 3, 1, 2, 4
• Subarrays of length 2: [3,1], [1,2], [2,4] → minimums: 1, 1, 2
• Subarrays of length 3: [3,1,2], [1,2,4] → minimums: 1, 1
• Subarrays of length 4: [3,1,2,4] → minimum: 1

Total sum: (3+1+2+4) + (1+1+2) + (1+1) + (1) = 17

Since the answer can be very large, return the result modulo 109 + 7.

Input & Output

example_1.py — Basic Array
$ Input: [3,1,2,4]
Output: 17
💡 Note: All 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.py — Single Element
$ Input: [11,81,94,43,3]
Output: 444
💡 Note: For each element, calculate how many subarrays it's the minimum for. Element 3 is minimum in many subarrays, contributing significantly to the total sum.
example_3.py — Edge Case
$ Input: [5]
Output: 5
💡 Note: Single element array has only one subarray [5] with minimum 5, so the answer is 5.

Constraints

  • 1 ≤ arr.length ≤ 3 × 104
  • 1 ≤ arr[i] ≤ 3 × 104
  • Return answer modulo 109 + 7

Visualization

Tap to expand
Restaurant Chain Revenue AnalysisRestaurant$3Restaurant$1Restaurant$2Restaurant$4Step 1: Find Impact Zones$3 impacts 1 left$1 impacts 2 left, 3 rightStep 2: Calculate Coverage• $3 restaurant: 1 × 1 = 1 segment (only [3])• $1 restaurant: 2 × 3 = 6 segments (dominates many)• $2 restaurant: 1 × 2 = 2 segments• $4 restaurant: 1 × 1 = 1 segmentStep 3: Total Revenue Impact$3×1 + $1×6 + $2×2 + $4×1 = $17Key Business InsightInstead of analyzing every possibleconsecutive restaurant segment,calculate each restaurant's totalimpact across all segments.✓ Monotonic stack finds nearestcompetitors efficiently⚡ O(n) time vs O(n³) brute force
Understanding the Visualization
1
Identify Impact Zones
For each restaurant, find how far its influence extends left and right
2
Calculate Coverage
Each restaurant affects left_distance × right_distance segments as the minimum
3
Sum Total Impact
Multiply each restaurant's value by its coverage area
Key Takeaway
🎯 Key Insight: Calculate each element's contribution by finding how many subarrays it dominates, rather than generating all subarrays explicitly. Use monotonic stack to efficiently find the nearest smaller elements on both sides.
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
28.6K Views
Medium-High Frequency
~25 min Avg. Time
892 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