Min Stack

Question (LC.155)

Design a data structure that supports push(x), pop(), top(), and getMin() all in O(1) time.

Example

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

Analysis

Besides the standard stack operations push(x), pop(), and peek(), we also need to support a heap operation getMin() in O(1) time. The first thought can be use a variable to keep track of the minimum value that works but when the min value gets popped out, we need to restore the second smallest value. This insight calls for a special type of stack - monotonic stack.

Monotonic Stack

A monotonic stack is a stack in which its elements are strictly increasing or decreasing. In this case, we want to use a decreasing stack to keep track of all the min values.

Illustration

We can use the example above.

Implementation

Max Stack (LC.716)

Design a data structure that supports push(x), pop(), top(), peekMax() and popMax().

Analysis

In addition to function like a normal max stack, its an additional function popMax(). Let's implement the normal functionalities first, then look into popMax(). It turns we really just have to brute force this with two stacks. Using a temp stack to store the elements until we find max and pop it. The tricky part is that we have to push it back and update incStack.

Consider example

Code

Last updated