Stack with minimum
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
Write a class MinStack: a stack of numbers with four methods.
push(n) puts n on top. pop() removes the top item (it doesn't need to return it). top() returns the top item. min() returns the smallest item in the whole stack.
Every method must be instant, O(1): min() can't look through the whole stack.
The tests build a new MinStack, call its methods in order, and check what each call returns. Calls that return nothing are shown as null.
Examples
Example 1
- Input
- calls = [["push", 5], ["push", 2], ["push", 8], ["min"], ["pop"], ["top"], ["pop"], ["min"]]
- Output
- [null, null, null, 2, null, 2, null, 5]
After pushing 5, 2, 8 the smallest is 2. Pop 8: the top is 2. Pop 2: now the smallest is 5.
Example 2
- Input
- calls = [["push", 3], ["push", 3], ["pop"], ["min"]]
- Output
- [null, null, null, 3]
Two 3s: popping one still leaves a 3 as the smallest.
Rules
pop,topandminare only called when the stack isn't empty.- Up to 150,000 calls per test. Numbers can be negative, and can repeat.
Words on this page, in plain English (3)Open if any word is new to you
- O(1): constant time
- Takes the same time no matter how big the input is. Like opening a book at page 1.
- Stack
- A pile where you only touch the top: add with
push, take withpop. The last thing in is the first out, like a pile of plates. - Test
- An example input with the answer it should give. Your code passes if it gives that answer.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
This time we write a class: a blueprint for an object with its own data and methods. The tests make one with new MinStack(), then call push, pop, top and min on it.
A normal stack can do the first three instantly. The challenge is min(): it must be instant too, so it can't look through every item.
2. Solve an example by hand
Push 5, 2, 8. The smallest is 2. Pop the 8: still 2. Pop the 2: now the smallest is 5.
The hard part is that last step. After popping the 2, how do we know the minimum is now 5, without searching?
3. The simple ways
- Search on every
min():Math.min(...this.items). Correct, but O(n) per call. A test with 50,000 calls on a big stack makes that billions of steps. - Keep one
smallestvariable, updated onpush. That handles pushes, but when you pop the smallest item, the variable is wrong, and you're back to searching.
4. Spot the pattern
Notice this: the minimum of a stack only depends on the items at or below the top. Items above have no say until they're pushed, and when they're popped, the minimum goes back to exactly what it was before.
So remember the minimum at every height, in a second stack that grows and shrinks with the first one.
5. The two-stack idea
push(n): pushnontoitems, and pushMath.min(n, current minimum)ontomins.pop(): pop both.min(): the top ofmins.
Two stacks, side by side
- call =
- –
- returns =
- –
items (stack, top first)
- empty
mins (stack, top first)
- empty
class MinStack { constructor() { this.items = []; this.mins = []; // mins[i] is the smallest of items[0] to items[i] } push(n) { this.items.push(n); const smallest = this.mins.length === 0 ? n : Math.min(n, this.min()); this.mins.push(smallest); } pop() { this.items.pop(); this.mins.pop(); } top() { return this.items[this.items.length - 1]; } min() { return this.mins[this.mins.length - 1]; }}Two empty stacks: one for the items, one for the minimum at each height.
6. The code, line by line
class MinStack { constructor() { this.items = []; this.mins = []; // mins[i] is the smallest of items[0] to items[i] }A class groups data with the methods that use it.
constructorruns once, whennew MinStack()is called.this.itemsandthis.minsbelong to that one object.push(n) { this.items.push(n); const smallest = this.mins.length === 0 ? n : Math.min(n, this.min()); this.mins.push(smallest); }Push onto both stacks. The new minimum is the smaller of
nand the minimum so far, or justnif the stack was empty.pop() { this.items.pop(); this.mins.pop(); }Pop both stacks together, so
minsalways has one entry per item.top() { return this.items[this.items.length - 1]; } min() { return this.mins[this.mins.length - 1]; }The top item, and the current minimum: each is just the last entry of its array.
7. How fast is it?
Every method is O(1). The cost is memory: the second stack doubles what we store, still O(n).
This trade appears often: when a question would need searching, store the answer as you go, so it's ready when asked.
Common mistakes
- Forgetting
this.Inside a class, the data lives on the object:this.items, notitems. - Only pushing onto
minswhen the new number is smaller. Then the stacks have different heights, andpopremoves the wrong minimum. (That version can be made to work, but it needs care with repeated values.)
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Stack with minimum
Read the 21 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
class MinStack { constructor() { this.items = []; this.mins = []; // mins[i] is the smallest of items[0] to items[i] } push(n) { this.items.push(n); const smallest = this.mins.length === 0 ? n : Math.min(n, this.min()); this.mins.push(smallest); } pop() { this.items.pop(); this.mins.pop(); } top() { return this.items[this.items.length - 1]; } min() { return this.mins[this.mins.length - 1]; }}