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.void push(int val)
pushes the elementval
onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.
You must implement a solution with O(1)
time complexity for each function.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
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
Constraints:
-231 <= val <= 231 - 1
- Methods
pop
,top
andgetMin
operations will always be called on non-empty stacks. - At most
3 * 104
calls will be made topush
,pop
,top
, andgetMin
.
SOLUTION:
Time Complexity:
The time complexity of the push
, pop
, top
, and getMin
methods is O(1), which means they have constant time complexity.
The code implements a MinStack
class that supports the following operations: push()
, pop()
, top()
, and getMin()
.
The
__init__(self)
method initializes theMinStack
object. It creates two empty lists,self.stack
andself.min_stack
, which will be used to store the elements of the stack and the minimum values, respectively.The
push(self, val: int) -> None
method is used to push an elementval
onto the stack. It appends theval
to theself.stack
list. Then, it determines the minimum value by comparingval
with the current minimum value stored inself.min_stack[-1]
(ifself.min_stack
is not empty). Ifself.min_stack
is empty, it means the pushed value is the first element, so it assignsval
as the minimum value. The minimum value is then appended toself.min_stack
.The
pop(self) -> None
method removes the top element from the stack. It uses thepop()
method to remove the top element fromself.stack
. It also removes the corresponding minimum value fromself.min_stack
using thepop()
method.The
top(self) -> int
method returns the top element of the stack without modifying the stack. It uses the index-1
to access the last element inself.stack
and returns it.The
getMin(self) -> int
method retrieves the minimum element in the stack. It uses the index-1
to access the last element inself.min_stack
and returns it.
Comments
Post a Comment