8f174dbf创建于 2025年12月27日历史提交

Recommended Time & Space Complexity

You should aim for a solution with O(1) time for each function call and O(n) space, where n is the maximum number of elements present in the stack.


Hint 1

A brute force solution would be to always check for the minimum element in the stack for the getMin() function call. This would be an O(n) approach. Can you think of a better way? Maybe O(n) extra space to store some information.


Hint 2

We can use a stack to maintain the elements. But how can we find the minimum element at any given time? Perhaps we should consider a prefix approach.


Hint 3

We use an additional stack to maintain the prefix minimum element. When popping elements from the main stack, we should also pop from this extra stack. However, when pushing onto the extra stack, we should push the minimum of the top element of the extra stack and the current element onto this extra stack.