Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack
class:
MinStack()
initializes the stack object.push(val)
pushes the elementval
onto the stack.pop()
removes the element on the top of the stack.top()
gets the top element of the stack.getMin()
retrieves the minimum element in the stack.
You must implement push
, pop
, top
, and getMin
in constant time.
Solution
To get the minimum element in constant time, we can use the stack to not only store the elements, but also the minimum element at the time of insertion. This way, we can always get the minimum element in constant time.
Implementation
Pseudocode
- Create a class
MinStack
that initializes a stack. - Implement
push
method that takes a value and pushes it to the stack.- If the stack is empty, set the minimum value to the value being pushed.
- Otherwise, set the minimum value to the minimum of the value being pushed and the current minimum value.
- Implement
pop
method that pops the top element from the stack. - Implement
top
method that returns the top element from the stack. - Implement
getMin
method that returns the minimum element from the stack.
Complexity Analysis
- Time Complexity
push
-O(1)
- The value is pushed to the stack in constant time.pop
-O(1)
- The top element is popped from the stack in constant time.top
-O(1)
- The top element is returned from the stack in constant time.getMin
-O(1)
- Because the minimum element is stored in the stack, it can be returned in constant time.
- Space Complexity -
O(n)
- In the worst case, the stack will containn
elements.