Skip to main content

Implement Queue using Stacks

Implement a FIFO queue using only two stacks. Think about: How can two stacks simulate queue behavior? Hint: Use one stack for push, another for pop/peek. Example: push(1), push(2) peek() → 1 (front of queue) pop() → 1 peek() → 2

I back a queue with two stacks. Pushing is easy; I move items across only when the output stack runs dry.

Examples

You write

MyQueue: push(x: int), pop(), peek(), empty()

  1. Example 1

    Input
    MyQueue(), push(1), push(2), peek() => 1, pop() => 1, empty() => false
    returns
    [1, 1, false]
  2. Example 2

    Input
    MyQueue(), push(1), peek() => 1, pop() => 1, empty() => true
    returns
    [1, 1, true]

The pattern behind it

Design

I reach for it when

  • The statement describes a class with methods, not one function.
  • Each method needs to be fast, and the structure decides how fast.

Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.

All 27 Design problems

Stack

I reach for it when

  • Things must close in the reverse order they opened.
  • You need the nearest earlier or later item that is bigger or smaller.

Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.

All 17 Stack problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Implement Queue using Stackseasy

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.