Skip to content
CodeKruPro

Build a queue from two stacks

Coding problemEasy-MediumAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft

Build a first-in-first-out queue using only two stacks. A stack can add a value on top, remove the top value, look at the top value and report its size.

Your function receives a list of commands and runs them in order on an empty queue:

  • "push x" adds the value x at the back of the queue;
  • "pop" removes the front value and outputs it;
  • "peek" outputs the front value without removing it;
  • "size" outputs how many values the queue holds.

"pop" and "peek" on an empty queue output -1. Return all outputs, in order. Every command should take constant time on average: the hidden tests hold 100,000 commands.

Examples

Example 1
Input: commands = ["push 1","push 2","peek","pop","size"]
Output: [1,1,1]
The front value is 1. After it is removed, one value is left.
Example 2
Input: commands = ["pop","push 5","pop","peek"]
Output: [-1,5,-1]
Example 3
Input: commands = ["push 3","push 4","pop","push 5","pop","pop"]
Output: [3,4,5]

Constraints

  • Between 1 and 100,000 commands
  • Every pushed value is between 0 and 1,000,000,000

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

to answer and keep your progress. Reading is free for everyone.