← Meta (Facebook) bank

Meta (Facebook) · Question 29 · Queues

Implement Queue using Stacks

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

Problem

You are required to implement a queue using only two stacks.

Approach

Push to s1; move everything to s2 only when s2 runs dry (amortized O(1)).

Time O(1)Space O(n)

How it works

  1. 1Enqueue always lands on s1.
  2. 2Dequeue drains s1 into s2 lazily, then pops.

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 3Branches 7Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatyesno↻ repeatyesnoyesnoyesnoyes↻ repeat↻ repeatyesnoSTARTCLASS MyQueueDEFINE __init__(self)self.s1 = []self.s2 = []DEFINE push(self, x)self.s1.append(x)DEFINE pop(self)if not self.s2while self.s1self.s2.append(self.s1.pop())RETURN self.s2.pop()DEFINE peek(self)if not self.s2while self.s1self.s2.append(self.s1.pop())RETURN self.s2[-1]DEFINE empty(self)RETURN len(self.s1) == 0and len(self.s2) == 0DEFINE 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/39

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