In this problem we’re told to create a stack that support the push,pop, top, and getMin operations. The operations must be done in O(1) constant time.
Example
Approach 1
Visualize the problem
The push, pop, and top operations can easily be done in O(1) time with using the built-in functions.
The getMin() function naively can be solved using O(n) time by iterating over the current version of the stack and comparing the min value. However since we wan’t a more optimal solution we can do the following
Since for each push and pop operation our min value changes we can keep a parallel stack to keep track of the earliest and latest min value of the stack . Meaning that when a value is added to the empty stack we say its the min value, as we add more values we compare again and determine the new min value at this position in the stack while ensuring we keep the previous min values.