← Deloitte bank

Deloitte · Question 47 · Queues

Implement Queue using Stacks

QueuesJavacode⏱ O(1)💾 O(n)
Service-based

Problem

Implement queue operations via two stacks.

Approach

inStack for enqueue, outStack for dequeue at amortized O(1).

Time O(1)Space O(n)

How it works

  1. 1Enqueue on in-stack.
  2. 2Drain to out-stack lazily for dequeue.

Sample input / output

Input:
ops = [push(1), push(2), peek(), pop(), empty()]
Output:
[1, 1, false]

Constraints

pop/peek on non-empty queue.

Solution — read it, then walk it

Time O(1)Space O(n)Loops 1Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class MyQueueDEFINE Stack<Integer> in =new Stack<>(), out = newStack<>()DEFINE void push(int x) {in.push(x); }DEFINE int pop() { peek();return out.pop(); }DEFINE int peek()if (out.isEmpty())while (!in.isEmpty())out.push(in.pop())RETURN out.peek()DEFINE boolean empty() {return in.isEmpty() &&out.isEmpty(); }DEFINE static voidmain(String[] args)MyQueue q = new MyQueue()q.push(1)q.push(2)System.out.println("[" +q.peek() + ", " + q.pop() +", " + q.empty() + "]")END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/18

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