← All coding problems
Implement Queue using Stacks
easyStack & Queue+10 XPTime limit 2s
Build a first-in-first-out queue using only two stacks (only push to top, pop from top, look at top, size/empty). Support:
push x— addxto the back of the queuepop— remove the front element and print itpeek— print the front elementempty— printtrueif the queue is empty, otherwisefalse
Input:
- line 1:
q - next
qlines: one operation each.popandpeekare only used when the queue is not empty.
Output: one line for every pop, peek and empty.
Constraints: 1 ≤ q ≤ 10⁵, −10⁴ ≤ x ≤ 10⁴.
The trick: push onto an in stack. To pop, take from an out stack — and only when out is empty, pour everything from in into out (which reverses the order). Each element moves at most twice, so every operation is amortised O(1).
Sample input 1
5 push 1 push 2 peek pop empty
Sample output 1
1 1 false
Sample input 2
4 empty push 5 pop empty
Sample output 2
true 5 true
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).