Workspace Candy
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Candy visualizer

Learn Candy with a step-by-step Greedy & Intervals visualizer, JavaScript source code and a worked example. Practice scheduling and resource allocation.

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

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let c=Array(a.length).fill(1);
for(let i=1;
i<a.length;
i++){
if(a[i]>a[i-1])c[i]=c[i-1]+1;
s("Left-to-right constraint",{
Ratings:a,Candy:c
},[i])
}
for(let i=a.length-2;
i>=0;
i--){
if(a[i]>a[i+1])c[i]=Math.max(c[i],c[i+1]+1);
s("Right-to-left constraint",{
Ratings:a,Candy:c
},[i])
}
return c.reduce((a,b)=>a+b,0)
};

Execution canvas

Active Changed
STEP 1

Left-to-right constraint

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

Ratings3 items
Candy3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Greedy & Intervals · Scheduling and resource allocation

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

[
  1,
  0,
  2
]

Execution steps

  1. Left-to-right constraint
  2. Right-to-left constraint

Computed output

5
JavaScript reference implementation
const solve = (a,s)=>{
  let c=Array(a.length).fill(1);
  for(let i=1;
  i<a.length;
  i++){
    if(a[i]>a[i-1])c[i]=c[i-1]+1;
    s("Left-to-right constraint",{
      Ratings:a,Candy:c
    },[i])
  }
  for(let i=a.length-2;
  i>=0;
  i--){
    if(a[i]>a[i+1])c[i]=Math.max(c[i],c[i+1]+1);
    s("Right-to-left constraint",{
      Ratings:a,Candy:c
    },[i])
  }
  return c.reduce((a,b)=>a+b,0)
};

Continue learning

Practice related DSA questions in the same topic.