DSA interview question
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.
class MyQueue {
public:
void push(int x);
int pop(); // called only when non-empty
int peek(); // called only when non-empty
bool empty();
};
| Operations | Output | Explanation |
|---|---|---|
push(1) push(2) peek() pop() empty() | 1 1 false | LeetCode's example |
push(1) push(2) push(3) pop() pop() pop() | 1 2 3 | First in, first out |
push(1) push(2) pop() push(3) pop() pop() | 1 2 3 | New 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.)
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