v9.1.1
Menu

Implement Queue using Stacks

easyPRODesign & StacksAmazon DSA

Implement a FIFO queue using only two stacks. Support push, pop (remove front), peek (get front), and empty.

Output the result of pop, peek, and empty operations.

Example

Input
push,1;push,2;peek;pop;empty
Output
1
1
False
Reasoning
  • The input is a sequence of operations separated by semicolons. push,1 means push the value 1; peek, pop and empty take no argument. Only peek, pop and empty produce a line of output, so three operations give three lines.
  • After push,1 and push,2 the queue holds [1,2][1, 2] from front to back: 1 arrived first, so it is at the front.
  • peek reports the front without removing it: 1. The queue is still [1,2][1, 2].
  • pop removes and reports the front: 1 again. The queue is now [2][2].
  • empty asks whether nothing is left. One element (2) remains, so it prints False.
  • Notice that a plain stack would have answered 2 to the first peek, because a stack serves the most recent arrival first. The two stacks together must reverse that order so the oldest element always comes out first.

Constraints

  • 1 <= val <= 9
  • At most 100 operations
  • All pop and peek calls are valid

Learn this in

More from Amazon DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.