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

Implement Queue Using Stacks visualizer

Learn Implement Queue Using Stacks 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 / 10Execution step
Reference example · JavaScript
Inspect reference input
[
  [
    "push",
    1
  ],
  [
    "push",
    2
  ],
  [
    "pop"
  ],
  [
    "push",
    3
  ],
  [
    "pop"
  ],
  [
    "pop"
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (ops,s)=>{
let a=[],b=[],o=[];
for(let [op,x] of ops){
if(op==="push")a.push(x);
else{
if(!b.length)while(a.length){
b.push(a.pop());
s("Transfer to output stack",{
Input:a,OutputStack:b
})
}
o.push(b.pop())
}
s("Execute "+op,{
Input:a,OutputStack:b,Results:o
})
}
return o
};

Execution canvas

Active Changed
STEP 1

Execute push

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

Input1 items
OutputStack0 items

Empty at this step.

Results0 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

[
  [
    "push",
    1
  ],
  [
    "push",
    2
  ],
  [
    "pop"
  ],
  [
    "push",
    3
  ],
  [
    "pop"
  ],
  [
    "pop"
  ]
]

Execution steps

  1. Execute push
  2. Transfer to output stack
  3. Execute pop

Computed output

[
  1,
  2,
  3
]
JavaScript reference implementation
const solve = (ops,s)=>{
  let a=[],b=[],o=[];
  for(let [op,x] of ops){
    if(op==="push")a.push(x);
    else{
      if(!b.length)while(a.length){
        b.push(a.pop());
        s("Transfer to output stack",{
          Input:a,OutputStack:b
        })
      }
      o.push(b.pop())
    }
    s("Execute "+op,{
      Input:a,OutputStack:b,Results:o
    })
  }
  return o
};

Continue learning

Practice related DSA questions in the same topic.