Workspace Implement Circular Queue
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Implement Circular Queue visualizer

Learn Implement Circular Queue with a step-by-step Stacks & Queues visualizer, JavaScript source code and a worked example. Practice operations and expressions.

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
{
  "capacity": 3,
  "ops": [
    [
      "push",
      1
    ],
    [
      "push",
      2
    ],
    [
      "pop"
    ],
    [
      "push",
      3
    ],
    [
      "push",
      4
    ],
    [
      "pop"
    ],
    [
      "pop"
    ],
    [
      "pop"
    ]
  ]
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
capacity,ops
},s)=>{
let a=Array(capacity).fill(null),h=0,n=0,o=[];
for(let [op,x] of ops){
if(op==="push"&&n<capacity){
a[(h+n)%capacity]=x;
n++
}else if(op==="pop"&&n){
o.push(a[h]);
a[h]=null;
h=(h+1)%capacity;
n--
}
s("Wrap indices modulo capacity",{
Buffer:a,Head:[h],Size:[n],Output:o
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Wrap indices modulo capacity

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

Buffer3 items
Head1 items
Size1 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 · Operations and expressions

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

{
  "capacity": 3,
  "ops": [
    [
      "push",
      1
    ],
    [
      "push",
      2
    ],
    [
      "pop"
    ],
    [
      "push",
      3
    ],
    [
      "push",
      4
    ],
    [
      "pop"
    ],
    [
      "pop"
    ],
    [
      "pop"
    ]
  ]
}

Execution steps

  1. Wrap indices modulo capacity

Computed output

[
  1,
  2,
  3,
  4
]
JavaScript reference implementation
const solve = ({
  capacity,ops
},s)=>{
  let a=Array(capacity).fill(null),h=0,n=0,o=[];
  for(let [op,x] of ops){
    if(op==="push"&&n<capacity){
      a[(h+n)%capacity]=x;
      n++
    }else if(op==="pop"&&n){
      o.push(a[h]);
      a[h]=null;
      h=(h+1)%capacity;
      n--
    }
    s("Wrap indices modulo capacity",{
      Buffer:a,Head:[h],Size:[n],Output:o
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.