DSA interview question
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.
class MyStack {
public:
void push(int x);
int pop(); // called only when non-empty
int top(); // called only when non-empty
bool empty();
};
| Operations | Output | Explanation |
|---|---|---|
push(1) push(2) top() pop() empty() | 2 2 false | LeetCode's example |
push(1) push(2) push(3) pop() pop() pop() | 3 2 1 | Last in, first out |
push(1) push(2) pop() push(3) top() | 2 3 | Interleaved |
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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in