Workspace Sum Of Subarray Ranges
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Sum of Subarray Ranges visualizer

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.

1 / 9Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    3,
    1,
    2,
    4
  ],
  "range": true
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
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)
};

Execution canvas

Active Changed
STEP 1

Count subarrays where popped value is extreme

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Array4 items
Stack1 items
Contribution1 items
Total1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Stacks & Queues · Monotonic structures

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

  1. 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)
};

Continue learning

Practice related DSA questions in the same topic.