Sum of Subarray Minimums
MediumStackmonotonic stack
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an integer array arr, consider every contiguous non-empty subarray. Return the sum of the minimum element of each subarray.
Because the sum can be very large, return it modulo 10^9 + 7.
Aim for O(n) time. An O(n^2) approach is too slow for the largest inputs.
Examples
Input: arr = [2,4,1]
Output: 11
The subarrays [2], [4], [1], [2,4], [4,1], [2,4,1] have minimums 2, 4, 1, 2, 1, 1, which sum to 11.
Input: arr = [5,5]
Output: 15
The subarrays [5], [5] and [5,5] each have minimum 5. Equal values must not be double-counted or skipped.
Constraints
- 1 <= arr.length <= 3 * 10^4
- 1 <= arr[i] <= 3 * 10^4
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.