All topics
54

A stack that also knows its smallest value

Tier 1Locked

Where it runs

1. The problem

A plain stack puts a value on, takes it off and shows the top in O(1). But it has no fast answer to "what is the smallest value in here right now?". You would have to look through the whole stack, which is O(n) for every question. And the question comes up all the time: the lowest price in a trading session, the minimum in a history you can undo, the smallest item while data is added and removed.

A min stack (a stack with a minimum) answers getMin in O(1). The idea behind it is small, and it helps in many places: keep the ready answer next to the data, and don't compute it again.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Design problems where a stack must answer an extra question in O(1), such as its smallest value. Store the answer for each level next to the value, so a pop brings back the old answer.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy