KatInterview

943. Sum of Subarray Minimums

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the sum of min(b) for every contiguous subarray b of arr. A naive approach of iterating through all O(N^2) subarrays and finding the minimum for each would be too slow, resulting in an O(N^3) or O(N^2) complexity, which is not feasible given the constraints (N <= 3 * 10^4).

Solution

Sum of Subarray Minimums in Python

class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        MOD = 10**9 + 7
        n = len(arr)
        
        # Use a monotonic stack to find the previous smaller or equal element.
        # The stack will store indices.
        stack = []
        
        # dp[i] will store the sum of minimums of all subarrays ending at index i.
        dp = [0] * n
        
        total_sum = 0
        
        for i in range(n):
            # Maintain a monotonic increasing stack of values.
            while stack and arr[stack[-1]] > arr[i]:
                stack.pop()
            
            # p is the index of the previous smaller or equal element.
            p = stack[-1] if stack else -1
            
            # Calculate dp[i]
            # 1. Contribution from subarrays where arr[i] is the new minimum.
            #    These are subarrays arr[j...i] where j is in (p, i].
            #    There are (i - p) such subarrays. Their sum of minimums is arr[i] * (i - p).
            contribution_new_min = arr[i] * (i - p)
            
            # 2. Contribution from subarrays where arr[i] is not the new minimum.
            #    These are subarrays arr[j...i] where j is in [0, p].
            #    The minimum of arr[j...i] is the same as min of arr[j...p].
            #    The sum of these minimums is dp[p].
            contribution_from_prev = dp[p] if p != -1 else 0
            
            dp[i] = contribution_from_prev + contribution_new_min
            
            total_sum = (total_sum + dp[i]) % MOD
            
            # Push current index to stack.
            stack.append(i)
            
        return total_sum

Sum of Subarray Minimums in Java

class Solution {
    public int sumSubarrayMins(int[] arr) {
        int n = arr.length;
        long MOD = 1_000_000_007;

        // Use a monotonic stack to find the previous smaller or equal element.
        // The stack will store indices.
        Stack<Integer> stack = new Stack<>();

        // dp[i] will store the sum of minimums of all subarrays ending at index i.
        long[] dp = new long[n];

        long totalSum = 0;

        for (int i = 0; i < n; i++) {
            // Maintain a monotonic increasing stack of values.
            while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
                stack.pop();
            }

            // p is the index of the previous smaller or equal element.
            int p = stack.isEmpty() ? -1 : stack.peek();

            // Calculate dp[i]
            // 1. Contribution from subarrays where arr[i] is the new minimum.
            //    These are subarrays arr[j...i] where j is in (p, i].
            //    There are (i - p) such subarrays. Their sum of minimums is arr[i] * (i - p).
            long contribution_new_min = (long) arr[i] * (i - p);

            // 2. Contribution from subarrays where arr[i] is not the new minimum.
            //    These are subarrays arr[j...i] where j is in [0, p].
            //    The minimum of arr[j...i] is the same as min of arr[j...p].
            //    The sum of these minimums is dp[p].
            long contribution_from_prev = (p == -1) ? 0 : dp[p];

            dp[i] = (contribution_from_prev + contribution_new_min) % MOD;

            totalSum = (totalSum + dp[i]) % MOD;

            // Push current index to stack.
            stack.push(i);
        }

        return (int) totalSum;
    }
}

Sum of Subarray Minimums in C++

class Solution {
public:
    int sumSubarrayMins(vector<int>& arr) {
        int n = arr.size();
        long long MOD = 1e9 + 7;
        
        // Use a monotonic stack to find the previous smaller or equal element.
        // The stack will store indices.
        stack<int> st;
        
        // dp[i] will store the sum of minimums of all subarrays ending at index i.
        vector<long long> dp(n);
        
        long long totalSum = 0;
        
        for (int i = 0; i < n; ++i) {
            // Maintain a monotonic increasing stack of values.
            while (!st.empty() && arr[st.top()] > arr[i]) {
                st.pop();
            }
            
            // p is the index of the previous smaller or equal element.
            int p = st.empty() ? -1 : st.top();
            
            // Calculate dp[i]
            // 1. Contribution from subarrays where arr[i] is the new minimum.
            //    These are subarrays arr[j...i] where j is in (p, i].
            //    There are (i - p) such subarrays. Their sum of minimums is arr[i] * (i - p).
            long long contribution_new_min = (long long)arr[i] * (i - p);
            
            // 2. Contribution from subarrays where arr[i] is not the new minimum.
            //    These are subarrays arr[j...i] where j is in [0, p].
            //    The minimum of arr[j...i] is the same as min of arr[j...p].
            //    The sum of these minimums is dp[p].
            long long contribution_from_prev = (p == -1) ? 0 : dp[p];
            
            dp[i] = (contribution_from_prev + contribution_new_min) % MOD;
            
            totalSum = (totalSum + dp[i]) % MOD;
            
            // Push current index to stack.
            st.push(i);
        }
        
        return totalSum;
    }
};

Sum of Subarray Minimums in TypeScript

function sumSubarrayMins(arr: number[]): number {
    const MOD = 10**9 + 7;
    const n = arr.length;

    // Use a monotonic stack to find the previous smaller or equal element.
    // The stack will store indices.
    const stack: number[] = [];

    // dp[i] will store the sum of minimums of all subarrays ending at index i.
    const dp: number[] = new Array(n).fill(0);

    let totalSum = 0;

    for (let i = 0; i < n; i++) {
        // Maintain a monotonic increasing stack of values.
        while (stack.length > 0 && arr[stack[stack.length - 1]] > arr[i]) {
            stack.pop();
        }

        // p is the index of the previous smaller or equal element.
        const p = stack.length > 0 ? stack[stack.length - 1] : -1;

        // Calculate dp[i]
        // 1. Contribution from subarrays where arr[i] is the new minimum.
        //    These are subarrays arr[j...i] where j is in (p, i].
        //    There are (i - p) such subarrays. Their sum of minimums is arr[i] * (i - p).
        const contribution_new_min = arr[i] * (i - p);

        // 2. Contribution from subarrays where arr[i] is not the new minimum.
        //    These are subarrays arr[j...i] where j is in [0, p].
        //    The minimum of arr[j...i] is the same as min of arr[j...p].
        //    The sum of these minimums is dp[p].
        const contribution_from_prev = (p === -1) ? 0 : dp[p];
        
        dp[i] = (contribution_from_prev + contribution_new_min) % MOD;

        totalSum = (totalSum + dp[i]) % MOD;

        // Push current index to stack.
        stack.push(i);
    }

    return totalSum;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.