Learn Sum of Subarray Ranges with a step-by-step Stacks & Queues visualizer, JavaScript source code and a worked example. Practice monotonic structures.
INTERACTIVE EXECUTION STUDIO
LEARN BY DOING
Predict. Execute. Understand.
Follow the source code, inspect live state changes, and predict the next operation before revealing it.
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"a": [
3,
1,
2,
4
],
"range": true
}
Execution steps
Count subarrays where popped value is extreme
Computed output
13
JavaScript reference implementation
const solve = ({
a,range
},s)=>{
function f(min){
let st=[],total=0;
for(let i=0;
i<=a.length;
i++){
while(st.length&&(i===a.length||(min?a[st.at(-1)]>a[i]:a[st.at(-1)]<a[i]))){
let j=st.pop(),l=st.at(-1)??-1;
total+=a[j]*(j-l)*(i-j);
s("Count subarrays where popped value is extreme",{
Array:a,Stack:st,Contribution:[a[j]*(j-l)*(i-j)],Total:[total]
},[j])
}
if(i<a.length)st.push(i)
}
return total
}
return range?f(false)-f(true):f(true)
};