← L&T Mindtree bank

L&T Mindtree · Question 29 · Queues

Implement Queue using Stacks

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

Problem

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

Approach

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

Time O(1)Space O(n)

How it works

  1. 1Enqueue on the in-stack.
  2. 2Drain to the 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 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yesnoSTARTimport java.util.*DEFINE class MainDEFINE class MyQueueDEFINE Stack<Integer>inStack = new Stack<>()DEFINE 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)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/20

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