29: Implement a min stack that supports finding the minimum element in O(1) time.
⏳⌚ 00:00:00

Question:-

Implement a min stack that supports finding the minimum element in O(1) time.
Example 1:
Input: according to question
Output: according to question

Steps to solve:-

1. Stack :-
A custom stack data structure called MyStack is defined. It contains the following main components:
stack int s: A standard C++ stack that will be used to store the elements. int minEle: A variable to keep track of the minimum element in the stack. The getMin method is used to print the minimum element of the stack. It checks if the stack is empty and, if not, it prints the value stored in the minEle variable, which represents the minimum element.
The peek method is used to print the top element of the stack. It checks if the stack is empty and, if not, it compares the top element t with minEle. If t is less than minEle, it prints minEle, which is still the minimum element, otherwise, it prints t.
The pop method is used to remove the top element from the stack. It first checks if the stack is empty and, if not, it pops the top element t. If t is less than minEle, it means that minEle represents the value of t (the minimum element), and it updates minEle accordingly. It prints the element that was removed from the stack.
The push method is used to insert a new element x into the stack. If the stack is empty, it sets minEle to x and pushes x onto the stack. If x is less than minEle, it pushes 2 * x - minEle onto the stack and updates minEle to x. Otherwise, it simply pushes x onto the stack.
2. In the main function:-
An instance of the custom stack, MyStack, is created as s.
Various operations are performed on the stack, such as pushing elements (3, 5, 2, 1), getting the minimum element, popping elements, and peeking at the top element.
The output of each operation is printed using cout.

solution->

View Code 1
Time Complexity = O(1)
Space Complexity = O(1)