Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack objectvoid push(int val)pushes the elementvalonto the stackvoid pop()removes the element on the top of the stackint top()gets the top element of the stackint getMin()retrieves the minimum element in the stack
You must implement a solution with O(1) time complexity for each function.
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
Constraints
-2³¹ <= val <= 2³¹ - 1- Methods
pop,topandgetMinoperations will always be called on non-empty stacks - At most
3 * 10⁴calls will be made topush,pop,top, andgetMin
How the tests work: each test is a sequence of calls.
operations[i]is the method called witharguments[i]; the first entry constructs the class. The expected output lists what every call returns —nullfor the constructor and for methods that return nothing.