← Google bank

Google · Question 43 · Queues

Implement Queue using Stacks

QueuesPythoncode⏱ O(1)💾 O(n)
Product-based

Problem

Implement a queue using two stacks supporting enqueue, dequeue, peek, and empty operations.

Approach

Use two stacks: one for enqueue and one for dequeue.

Time O(1)Space O(n)

How it works

  1. 1Push elements onto in_stack.
  2. 2Pop/peek from out_stack.
  3. 3Transfer all elements from in_stack to out_stack when out_stack is empty.
  4. 4Check emptiness via both stacks.

Sample input / output

Input:
5
push 1
push 2
peek
pop
empty
Output:
[1, 1, False]

Constraints

1 <= x <= 9; at most 100 calls; pop/peek assume the queue is non-empty.

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.
yesno↻ repeatyesnoyesnoyesnoyes↻ repeat↻ repeatyesnoSTARTCLASS MyQueueDEFINE __init__(self)self.in_stack = []self.out_stack = []DEFINE push(self, x)self.in_stack.append(x)DEFINE pop(self)self.peek()RETURN self.out_stack.pop()DEFINE peek(self)if not self.out_stackwhile self.in_stackself.out_stack.append(self.in_stack.pop())RETURN self.out_stack[-1]DEFINE empty(self)RETURN not self.in_stackand not self.out_stackDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)ops = int(next(it))q = MyQueue()out = []for _ in range(ops)op = next(it)if op == 'push'q.push(int(next(it)))elif op == 'pop'out.append(q.pop())elif op == 'peek'out.append(q.peek())elif op == 'empty'out.append(q.empty())print(out)if __name__ =="__main__"main()END
  • 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