Sum of Subarray Minimums

Pattern: Monotonic stack

medium

Each value is the minimum of every subarray that stays inside its reach: from just after the previous smaller value to just before the next smaller-or-equal value. It contributes value × left × right. Monotonic stacks give both distances in O(n).

The problem

Return the sum of min(subarray) over every contiguous subarray of arr, modulo 10^9 + 7. [3, 1, 2, 4] gives 17.

Think first

  • Instead of each subarray, can you ask about each value?
  • For which subarrays is arr[i] the minimum?
  • With equal values, which copy should own a subarray?

Hints

    Brute force, and why it fails

    Every subarray with a running minimum: O(n²).

    The key insight

    Count by contribution. A monotonic stack gives each value's previous smaller and next smaller in one pass each.

    Dry run

    30 
    11 
    22 
    43 
    total3

    arr = [3, 1, 2, 4]. For 3: no smaller on the left (left = 1), the next smaller is 1 one step right (right = 1). 3 × 1 × 1 = 3.

    Step 1 of 4

    The plan

    left[i]  = i - (index of previous strictly smaller), or i + 1
    right[i] = (index of next smaller or equal) - i, or n - i
    answer   = sum of arr[i] * left[i] * right[i], mod 1e9+7
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Two monotonic-stack passes and one sum.

    Edge cases

    • All equal values: the tie rule keeps each subarray counted once.
    • One value.
    • Large sums: take the modulo, and use 64-bit products.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int sumSubarrayMins(int[] arr) {
            final long MOD = 1_000_000_007L;
            int n = arr.length;
            int[] left = new int[n], right = new int[n];    // how far each value stays the minimum on each side
            Deque<Integer> st = new ArrayDeque<>();
            for (int i = 0; i < n; i++) {                   // previous strictly smaller value
                while (!st.isEmpty() && arr[st.peek()] >= arr[i]) st.pop();
                left[i] = st.isEmpty() ? i + 1 : i - st.peek();
                st.push(i);
            }
            st.clear();
            for (int i = n - 1; i >= 0; i--) {              // next smaller-or-equal value (ties counted once)
                while (!st.isEmpty() && arr[st.peek()] > arr[i]) st.pop();
                right[i] = st.isEmpty() ? n - i : st.peek() - i;
                st.push(i);
            }
            long total = 0;
            for (int i = 0; i < n; i++) total = (total + (long) arr[i] * left[i] % MOD * right[i]) % MOD;
            return (int) total;
        }
    }

    C++

    class Solution {
    public:
        int sumSubarrayMins(vector<int>& arr) {
            const long long MOD = 1000000007LL;
            int n = static_cast<int>(arr.size());
            vector<long long> left(n), right(n);            // how far each value stays the minimum on each side
            stack<int> st;
            for (int i = 0; i < n; i++) {                   // previous strictly smaller value
                while (!st.empty() && arr[st.top()] >= arr[i]) st.pop();
                left[i] = st.empty() ? i + 1 : i - st.top();
                st.push(i);
            }
            while (!st.empty()) st.pop();
            for (int i = n - 1; i >= 0; i--) {              // next smaller-or-equal value (ties counted once)
                while (!st.empty() && arr[st.top()] > arr[i]) st.pop();
                right[i] = st.empty() ? n - i : st.top() - i;
                st.push(i);
            }
            long long total = 0;
            for (int i = 0; i < n; i++) total = (total + arr[i] * left[i] % MOD * right[i]) % MOD;
            return static_cast<int>(total);
        }
    };

    Python

    class Solution:
        def sumSubarrayMins(self, arr: list[int]) -> int:
            MOD = 1_000_000_007
            n = len(arr)
            left, right, st = [0] * n, [0] * n, []  # how far each value stays the minimum on each side
            for i in range(n):                      # previous strictly smaller value
                while st and arr[st[-1]] >= arr[i]:
                    st.pop()
                left[i] = i + 1 if not st else i - st[-1]
                st.append(i)
            st = []
            for i in range(n - 1, -1, -1):          # next smaller-or-equal value (ties counted once)
                while st and arr[st[-1]] > arr[i]:
                    st.pop()
                right[i] = n - i if not st else st[-1] - i
                st.append(i)
            return sum(arr[i] * left[i] * right[i] for i in range(n)) % MOD

    Common mistakes

    • Using strict comparisons on both sides, which counts ties twice.
    • Multiplying three ints without 64-bit types.

    Similar problems