PPractick

DSA interview question

Implement a Queue Using Stacks

Easy · Data structures · Topics: queue, stack

The problem

A functional-programming runtime only offers immutable stacks, but a job scheduler built on it needs a FIFO queue (push, pop, peek, empty). Two stacks solve it: an input stack receives pushes, and an output stack serves pops. When the output stack runs dry, pour the entire input stack into it, which reverses the order so the oldest element ends up on top. Each element is moved at most once, so every operation is amortised O(1).

Example: push(1), push(2), peek() → 1, pop() → 1, empty() → false.

Function signature

class MyQueue {
public:
    void push(int x);
    int pop();      // called only when non-empty
    int peek();     // called only when non-empty
    bool empty();
};

Test cases

OperationsOutputExplanation
push(1) push(2) peek() pop() empty()1 1 falseLeetCode's example
push(1) push(2) push(3) pop() pop() pop()1 2 3First in, first out
push(1) push(2) pop() push(3) pop() pop()1 2 3New pushes wait behind older ones
push(9) peek() empty()9 false
push(4) pop() empty()4 true

(Confirm: only stack operations may be used; pop and peek are never called on an empty queue; amortised O(1) is expected.)

How interviewers phrase it

Clarifying questions to ask

  1. Which stack operations are allowed? (push, pop, top, size, empty.)
  2. Is amortised O(1) acceptable, or must each operation be worst-case O(1)?
  3. Can pop or peek be called on an empty queue?

Follow-ups to expect

  1. "When do you transfer from in to out?"
  2. "Why is it amortised O(1)?"
  3. "What's the worst case for a single operation?"
  4. "What's the naive approach?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in