DSA interview question
A trading dashboard keeps a stack of recent price ticks. Traders can undo (pop) the latest tick, and the header must always show the lowest price currently on the stack, updated instantly. Scanning the stack for the minimum is O(n) per query. The fix is to remember, alongside each element, the minimum of the stack at the moment it was pushed. The minimum of the whole stack is then just the minimum stored with the top element, and popping automatically restores the previous minimum.
Example: push(-2), push(0), push(-3), getMin() → -3, pop(), top() → 0, getMin() → -2.
class MinStack {
public:
void push(int x);
void pop(); // called only when non-empty
int top(); // called only when non-empty
int getMin(); // called only when non-empty
};
| Operations | Output | Explanation |
|---|---|---|
push(-2) push(0) push(-3) getMin() pop() top() getMin() | -3 0 -2 | LeetCode's example |
push(5) push(3) push(7) getMin() pop() getMin() pop() getMin() | 3 3 5 | |
push(2) push(2) push(1) pop() getMin() | 2 | Duplicate minimums |
push(INT_MIN) push(INT_MAX) getMin() top() | -2147483648 2147483647 | Extreme values |
push(1) top() getMin() | 1 1 |
(Confirm: every operation must be O(1); pop, top and getMin 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