Sum of Subarray Minimums
Problem Statement
You are given an integer array arr.
Look at every contiguous subarray of arr. Take the minimum of each one and add all those minimums together. The total can be huge, so return it modulo 10^9 + 7.
An integer array arr.
The sum of min(subarray) over all subarrays, modulo 10^9 + 7.
The subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Their minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1, which add up to 17.
- • 1 ≤ arr.length ≤ 3 · 10^4
- • 1 ≤ arr[i] ≤ 3 · 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Fix the start, extend the end, add the running minimum each time
arr[i] is the min of left[i] × right[i] subarrays; find both counts with a monotonic stack
Fix the start of the subarray. Move the end one step at a time and keep the running minimum. Each (start, end) pair is one subarray, so add the current minimum to the total.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.