#907

Sum of Subarray Minimums

Medium
ArrayDynamic ProgrammingStackMonotonic StackMonotonic StackDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a monotonic stack to efficiently calculate how many subarrays each element is the minimum for. This reduces the need to explicitly generate all subarrays.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a stack and an array to store the contribution of each element.
  2. 2Step 2: For each element, determine how many subarrays it is the minimum for using the stack to find the previous and next smaller elements.
  3. 3Step 3: Calculate the contribution of each element to the total sum based on its position and the number of subarrays it is the minimum for.
  4. 4Step 4: Return the total sum modulo 10^9 + 7.
solution.py32 lines
1# Full working Python code
2
3def sumSubarrayMinimums(arr):
4    MOD = 10**9 + 7
5    n = len(arr)
6    stack = []
7    total_sum = 0
8    left = [0] * n
9    right = [0] * n
10
11    for i in range(n):
12        while stack and arr[stack[-1]] > arr[i]:
13            stack.pop()
14        left[i] = i + 1 if not stack else i - stack[-1]
15        stack.append(i)
16
17    stack.clear()
18
19    for i in range(n - 1, -1, -1):
20        while stack and arr[stack[-1]] >= arr[i]:
21            stack.pop()
22        right[i] = n - i if not stack else stack[-1] - i
23        stack.append(i)
24
25    for i in range(n):
26        total_sum += arr[i] * left[i] * right[i]
27        total_sum %= MOD
28
29    return total_sum
30
31# Example usage
32print(sumSubarrayMinimums([3, 1, 2, 4]))

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times (once for left and once for right). The space complexity is O(n) due to the additional arrays used to store left and right counts.

  • 1Using a monotonic stack can significantly reduce the time complexity.
  • 2Understanding how to calculate contributions of each element is key.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.