How can be time complexity of be o(1) to find minimum element of stack.
What is minimum time complexity?
@Deepanshu_garg
Minimum time complexity to find the minimum element at any instance in a stack is O(1).
If it is just time you want to save and you are not concerned about the space , you can easily achieve this by making a new stack and storing min element in the second stack. Everytime you push a new element into first stack ( main stack which has the elements ) , you compare the new element with the top of the second stack ( which stores the min elements ) and if it is lesser , it becomes the new minimum or else you just push the top element in the stack again. While popping , you pop elements from both the stacks as well.
At any instance if you get a query about printing the min element , you just print the top of the second stack.
There is , however a much better method which can do this problem in O(1) time as well as O(1) space but is slightly complicated. I request you to watch the tutorial video titled “Stack Get Minimum In Const Time And Space Hint” . It is the last video in the Stacks & Queues section. Kindly refer to it and try to implement it in code. Let me know if you have any doubts regarding it.