https://leetcode.com/problems/min-stack/
The problem asks us to extend stack’s API – so that in addition to being able to return the top, we can also look up the minimum number.
The most straightforward (and inefficient solution) would be to keep a separate store that mimics operations on the main stack – but instead of storing the actual values, this stack would only store the minimum at the top – comparing each newly inserted value with the current min. The obvious problem with this solution is the fact that we are wasting space by possibly repeatedly inserting the same value into the stack.
Instead, we should only insert into the minStack if the current value happens to be lesser than current min. When we pop, we need to update the minStack variable if the value being popped is the current min. This gives us O(1) time and O(n) space solution – note that the space complexity still stays at O(n) since in the worst case (when the numbers are sorted in descending order), we would still end up duplicating every value twice in both data structures.