Skip to the solution
EasyDSAAsked in 20246 min read

Design a Stack That Supports getMin() in O(1) (Min Stack)

1.1k views

The problem

Problem, as an interviewer would state it: "Design a stack supporting push, pop, top, and getMin — all in O(1) time, including getMin, which must return the current minimum value in the stack at any point."

Examples:

Code
const s = new MinStack();
s.push(5); s.push(2); s.push(7);
s.getMin(); // 2

Clarifying questions expected:

  • Is a genuine O(1) time requirement for getMin specifically the real, hard constraint here — would scanning the whole stack on each call be acceptable?
  • After popping the CURRENT minimum off the stack, does getMin need to correctly revert to the PREVIOUS minimum?
  • Should duplicate values (the same number pushed twice) be handled correctly if one of them happens to be the current minimum?

Code / implementation expected: Yes — real, direct proof that getMin runs in O(1) and correctly reverts to the previous minimum after the current minimum is popped off.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: MinStack's getMin() runs in O(1) and correctly reverts to the previous minimum after the current minimum is popped off

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 24 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Partial application bindings

Continue