Workspace Sliding Window Maximum
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Sliding Window Maximum visualizer

Learn Sliding Window Maximum 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": [
    1,
    3,
    -1,
    -3,
    5,
    3,
    6,
    7
  ],
  "k": 3
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let q=[],o=[];
for(let i=0;
i<a.length;
i++){
while(q.length&&q[0]<=i-k)q.shift();
while(q.length&&a[q.at(-1)]<=a[i])q.pop();
q.push(i);
if(i>=k-1)o.push(a[q[0]]);
s("Maintain decreasing deque",{
Array:a,Deque:q,Output:o
},[i])
}
return o
};

Execution canvas

Active Changed
STEP 1

Maintain decreasing deque

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

Array8 items
Deque1 items
Output0 items

Empty at this step.

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": [
    1,
    3,
    -1,
    -3,
    5,
    3,
    6,
    7
  ],
  "k": 3
}

Execution steps

  1. Maintain decreasing deque

Computed output

[
  3,
  3,
  5,
  5,
  6,
  7
]
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let q=[],o=[];
  for(let i=0;
  i<a.length;
  i++){
    while(q.length&&q[0]<=i-k)q.shift();
    while(q.length&&a[q.at(-1)]<=a[i])q.pop();
    q.push(i);
    if(i>=k-1)o.push(a[q[0]]);
    s("Maintain decreasing deque",{
      Array:a,Deque:q,Output:o
    },[i])
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.