Implement Queue using Stacks

Build a first-in-first-out queue using only two stacks. Support push (add to the back), pop (remove from the front), peek (read the front) and empty, using only standard stack operations.

30:00

Implement Queue using Stacks
easy
Free written solution
Topics
Companies

Build a first-in-first-out queue using only two stacks. Support push (add to the back), pop (remove from the front), peek (read the front) and empty, using only standard stack operations.

Example 1:
Input: {"commands":["MyQueue","push","push","peek","pop","empty"],"values":[[],[1],[2],[],[],[]]}
Output: [null,null,null,1,1,false]
Constraints:
  • 1≤x≤91 \leq x \leq 9

  • At most 100100 calls are made to push, pop, peek, and empty.

  • Every call to pop and peek is valid (the queue is not empty).

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["MyQueue","push","push","peek","pop","empty"],"values":[[],[1],[2],[],[],[]]}
new
push(1)
push(2)
peek()
pop()
empty()

6 calls to run. Watch which stack each value sits in and when it moves.

in

new values land here

empty

size 0

→

pour when out is empty

out

front of queue on top

empty

size 0

What the caller sees (front to back)

front

(empty)

back

Returned values

[]

moves in → out

0

each value moves at most once (2 pushes)

Variables
VariableValue
call
inStack[]
outStack[]
output[]
DepthFunction Call
Stack empty
0/12