← Microsoft bank

Microsoft · Question 28 · Queues

Implement Queue using Stacks

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

Problem

Implement a queue using two stacks.

Approach

Push to in-stack; drain to out-stack lazily for pop/peek.

Time O(1)Space O(n)

How it works

  1. 1Enqueue always lands on the in-stack.
  2. 2Dequeue drains to the out-stack only when dry.

Sample input / output

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

Constraints

1 <= x <= 9; pop/peek on non-empty queue.

Solution — read it, then walk it

Time O(1)Space O(n)Loops 2Branches 5Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE class MyQueueStack<Integer> inStack =new Stack<>()Stack<Integer> outStack =new Stack<>()DEFINE void push(int x) {inStack.push(x); }DEFINE int pop()peek()RETURN outStack.pop()DEFINE int peek()if(outStack.isEmpty())while(!inStack.isEmpty())outStack.push(inStack.pop())RETURN outStack.peek()DEFINE boolean empty() {return inStack.isEmpty() &&outStack.isEmpty(); }DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE ops = sc.nextInt()MyQueue q = new MyQueue()java.util.List<Object> out= new ArrayList<>()for (int i = 0; i <ops; i++)String op = sc.next()if (op.equals("push"))q.push(sc.nextInt())else if(op.equals("pop"))out.add(q.pop())else if(op.equals("peek"))out.add(q.peek())else if(op.equals("empty"))out.add(q.empty())System.out.println(out)END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/28

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