Uber · Question 31 · Queues
Implement Queue using Stacks
Problem
Implement a FIFO queue using two stacks. Support push, pop, peek, and empty operations.
Approach
Use two stacks: in_stack for enqueue (push), out_stack for dequeue (pop) and peek. Transfer elements from in_stack to out_stack when out_stack is empty.
Time O(1)Space O(n)
How it works
- 1Push onto in_stack.
- 2Pop/peek from out_stack, refilling it when empty.
- 3Empty only when both stacks are empty.
Sample input / output
Input: 5 push 1 push 2 peek pop empty Output: [1, 1, False]
Constraints
1 <= x <= 9; <= 100 calls; pop/peek on non-empty queue.
Solution — read it, then walk it
Time O(1)Space O(n)Loops 2Branches 6Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/37
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits