medium +30 pts

Sum of Subarray Minimums

Compute the sum of the minimum value over every contiguous subarray, modulo 10^9+7.

Given a list of integers `arr`, define the **minimum of a subarray** as the smallest element in that contiguous subarray. Your task is to compute the sum of the minimums over **all contiguous subarrays** of `arr`. Since the answer may be very large, return the sum modulo `10**9 + 7`. You must implement the function: ```python def sum_subarray_mins(arr: list[int]) -> int: ``` **Input:** - `arr`: a list of integers with length `n` (1 <= n <= 10^5). - Each element satisfies `-10^9 <= arr[i] <= 10^9`. **Output:** - Return an integer, the sum of all subarray minimums modulo `10**9 + 7`. **Definition:** A contiguous subarray is defined by a start index `i` and an end index `j` with `0 <= i <= j < n`. The number of subarrays is `n*(n+1)/2`. **Example:** For `arr = [3,1,2]`, all subarrays and their minimums are: - [3] -> 3 - [1] -> 1 - [2] -> 2 - [3,1] -> 1 - [1,2] -> 1 - [3,1,2] -> 1 Sum = 3+1+2+1+1+1 = 9. **Note:** A naive enumeration of all subarrays is not efficient enough. An O(n) or O(n log n) solution is expected.

Constraints

1 <= len(arr) <= 10^5 -10^9 <= arr[i] <= 10^9 Modulo value: 10^9 + 7

Example

>>> sum_subarray_mins([3,1,2])
9
>>> sum_subarray_mins([1,2,3])
14
>>> sum_subarray_mins([1,1,1])
6
>>> sum_subarray_mins([11,81,94,43,3])
444
30 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

For each element, think about how many subarrays have this element as the minimum.
Use a monotonic stack to find the previous smaller and next smaller element indices.
Be careful with duplicate values: define 'strictly smaller' on one side and 'smaller or equal' on the other to avoid double counting.
The contribution of arr[i] is arr[i] * (i - prev_smaller) * (next_smaller - i).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.