DSA interview question
A risk engine scores a price series by summing, over every contiguous window, the lowest price in that window, reported modulo 10⁹ + 7. There are O(n²) windows, so enumerating them is too slow for n = 3·10⁴. Flip the question: for each element, in how many windows is it the minimum? It is the minimum of windows that start after the previous smaller element and end before the next smaller element. Monotonic stacks find those boundaries in O(n), and the contribution is a[i] × (#choices of start) × (#choices of end).
Example: [3, 1, 2, 4] → 17.
int sumSubarrayMins(const vector<int>& arr); // modulo 1e9 + 7
| Input | Output | Explanation |
|---|---|---|
[3, 1, 2, 4] | 17 | 3 + 1 + 2 + 4 + 1 + 1 + 2 + 1 + 1 + 1 |
[11, 81, 94, 43, 3] | 444 | |
[1, 2, 3] | 10 | |
[2, 2, 2] | 12 | 6 windows, each with minimum 2; ties must be counted once |
[1] | 1 |
(Confirm: every non-empty contiguous subarray counts once; values are positive; the result is taken modulo 1,000,000,007.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in