Sum of Subarray Minimums - Monotonic Stack Pattern
Sum of Subarray Minimums in Java using the Monotonic Stack pattern: problem statement, approach, template, complexity, and interview tips.
Sum of Subarray Minimums
Problem Statement
Return the sum of the minimum value of every contiguous subarray, modulo 1,000,000,007.
Pattern: Monotonic Stack
Keep a stack of indices whose values are in increasing or decreasing order to find the next greater or smaller element efficiently.
Use this pattern when you need the next or previous greater or smaller element, or span and histogram style answers.
Approach
- Iterate through the array while keeping a stack of indices.
- Pop while the current value breaks the monotonic order and resolve the popped index.
- Push the current index and continue.
Pattern Template (Java)
Deque<Integer> stack = new ArrayDeque<>(); // stores indices
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
int idx = stack.pop();
// nums[i] is the next greater element of nums[idx]
}
stack.push(i);
}
Adapt this template to the exact rules of Sum of Subarray Minimums: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(n) time because each index is pushed and popped once; O(n) space.
Interview Tips
- Decide between storing values and storing indices, since indices are needed for distances.
- Handle elements left on the stack after the loop.
- Start with a brute-force idea, state its complexity, then explain how the Monotonic Stack pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
Continue Learning
Parent: DSA Interview Learning Path | Previous: Online Stock Span
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.