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 elementvalonto 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,topandgetMinoperations will always be called on non-empty stacks. - At most
3 * 104calls 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 theMinStackobject. It creates two empty lists,self.stackandself.min_stack, which will be used to store the elements of the stack and the minimum values, respectively.The
push(self, val: int) -> Nonemethod is used to push an elementvalonto the stack. It appends thevalto theself.stacklist. Then, it determines the minimum value by comparingvalwith the current minimum value stored inself.min_stack[-1](ifself.min_stackis not empty). Ifself.min_stackis empty, it means the pushed value is the first element, so it assignsvalas the minimum value. The minimum value is then appended toself.min_stack.The
pop(self) -> Nonemethod 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_stackusing thepop()method.The
top(self) -> intmethod returns the top element of the stack without modifying the stack. It uses the index-1to access the last element inself.stackand returns it.The
getMin(self) -> intmethod retrieves the minimum element in the stack. It uses the index-1to access the last element inself.min_stackand returns it.

Comments
Post a Comment