← Uber bank

Uber · Question 29 · Stacks

Implement Stack using Queues

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

Problem

Implement a LIFO stack using only two queues.

Approach

Use two queues. Push normally. For pop/top, move all but one to second queue, then return or remove last.

Time O(1)Space O(n)

How it works

  1. 1Push always lands on the active queue.
  2. 2Pop/top drain all but one element to the spare queue.
  3. 3Swap the queues so the spare becomes active.

Sample input / output

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

Constraints

1 <= x <= 9; <= 100 calls; queue-only operations inside.

Solution — read it, then walk it

Time O(1)Space O(n)Loops 3Branches 5Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatyesnoyesnoyesnoyes↻ repeat↻ repeatyesnoSTARTfrom collections importdequeCLASS MyStackDEFINE __init__(self)self.q1 = deque()self.q2 = deque()DEFINE push(self, x: int)-> Noneself.q1.append(x)DEFINE pop(self) -> intwhile len(self.q1) > 1self.q2.append(self.q1.popleft())res = self.q1.popleft()self.q1, self.q2 = self.q2,self.q1RETURN resDEFINE top(self) -> intwhile len(self.q1) > 1self.q2.append(self.q1.popleft())res = self.q1.popleft()self.q2.append(res)self.q1, self.q2 = self.q2,self.q1RETURN resDEFINE empty(self) -> boolRETURN not self.q1 and notself.q2DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)ops = int(next(it))st = MyStack()out = []for _ in range(ops)op = next(it)if op == 'push'st.push(int(next(it)))elif op == 'pop'out.append(st.pop())elif op == 'top'out.append(st.top())elif op == 'empty'out.append(st.empty())print(out)if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/43

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