Workspace Max Consecutive Ones Iii
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Max Consecutive Ones III visualizer

Learn Max Consecutive Ones III with a step-by-step Sliding Window & Two Pointers visualizer, JavaScript source code and a worked example. Practice fixed and variable windows.

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 / 12Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    1,
    1,
    1,
    0,
    0,
    0,
    1,
    1,
    1,
    1,
    0
  ],
  "k": 2,
  "mode": "zeros"
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k,mode
},s)=>{
let m=new Map,l=0,b=0;
for(let r=0;
r<a.length;
r++){
let x=a[r];
m.set(x,(m.get(x)||0)+1);
const invalid=()=>mode==="zeros"?(m.get(0)||0)>k:mode==="distinct"?m.size>k:r-l+1-Math.max(...m.values())>k;
while(invalid()){
let y=a[l++];
m.set(y,m.get(y)-1);
if(!m.get(y))m.delete(y)
}
b=Math.max(b,r-l+1);
s("Expand and shrink valid window",{
Array:[...a],Bounds:[l,r],Best:[b]
},[l,r])
}
return b
};

Execution canvas

Active Changed
STEP 1

Expand and shrink valid window

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

Array11 items
Bounds2 items
Best1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Sliding Window & Two Pointers · Fixed and variable windows

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,
    1,
    1,
    0,
    0,
    0,
    1,
    1,
    1,
    1,
    0
  ],
  "k": 2,
  "mode": "zeros"
}

Execution steps

  1. Expand and shrink valid window

Computed output

6
JavaScript reference implementation
const solve = ({
  a,k,mode
},s)=>{
  let m=new Map,l=0,b=0;
  for(let r=0;
  r<a.length;
  r++){
    let x=a[r];
    m.set(x,(m.get(x)||0)+1);
    const invalid=()=>mode==="zeros"?(m.get(0)||0)>k:mode==="distinct"?m.size>k:r-l+1-Math.max(...m.values())>k;
    while(invalid()){
      let y=a[l++];
      m.set(y,m.get(y)-1);
      if(!m.get(y))m.delete(y)
    }
    b=Math.max(b,r-l+1);
    s("Expand and shrink valid window",{
      Array:[...a],Bounds:[l,r],Best:[b]
    },[l,r])
  }
  return b
};

Continue learning

Practice related DSA questions in the same topic.