Workspace Sort Colors
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Sort Colors visualizer

Learn Sort Colors with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

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 / 7Execution step
Reference example · JavaScript
Inspect reference input
[
  2,
  0,
  2,
  1,
  1,
  0
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let l=0,i=0,r=a.length-1;
while(i<=r){
if(a[i]===0){
[a[l],a[i]]=[a[i],a[l]];
l++;
i++
}else if(a[i]===2){
[a[r],a[i]]=[a[i],a[r]];
r--
}else i++;
s("Maintain three regions",{
Array:a,Bounds:[l,i,r]
},[i])
}
return a
};

Execution canvas

Active Changed
STEP 1

Maintain three regions

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

Array6 items
Bounds3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

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

[
  2,
  0,
  2,
  1,
  1,
  0
]

Execution steps

  1. Maintain three regions

Computed output

[
  0,
  0,
  1,
  1,
  2,
  2
]
JavaScript reference implementation
const solve = (a,s)=>{
  let l=0,i=0,r=a.length-1;
  while(i<=r){
    if(a[i]===0){
      [a[l],a[i]]=[a[i],a[l]];
      l++;
      i++
    }else if(a[i]===2){
      [a[r],a[i]]=[a[i],a[r]];
      r--
    }else i++;
    s("Maintain three regions",{
      Array:a,Bounds:[l,i,r]
    },[i])
  }
  return a
};

Continue learning

Practice related DSA questions in the same topic.