PPractick

DSA interview question

Implement a Stack Using Queues

Easy · Data structures · Topics: stack, queue

The problem

A message broker's SDK only exposes a FIFO queue primitive, but one feature (undoing the most recent actions) needs LIFO behaviour. The task is to build a stack (push, pop, top, empty) on top of queue operations only: push to back, pop from front, peek at the front, size. The standard trick uses a single queue: after pushing a new element, rotate all the older elements behind it, so the newest element is always at the front, where pop and top can reach it in O(1).

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

Function signature

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

Test cases

OperationsOutputExplanation
push(1) push(2) top() pop() empty()2 2 falseLeetCode's example
push(1) push(2) push(3) pop() pop() pop()3 2 1Last in, first out
push(1) push(2) pop() push(3) top()2 3Interleaved
push(5) top() empty()5 false
push(4) pop() empty()4 true

(Confirm: only standard queue operations may be used; pop and top are never called on an empty stack.)

How interviewers phrase it

Clarifying questions to ask

  1. Which queue operations are allowed? (push to back, pop from front, front, size, empty.)
  2. Which operation should be cheap: push or pop?
  3. Can pop or top be called on an empty stack?

Follow-ups to expect

  1. "How does the one-queue version work?"
  2. "What's the two-queue version?"
  3. "Can you make push O(1) instead?"
  4. "Which is better?"
  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