How to Design a Min Stack with O(1) getMin() Using Two Stacks
A Min Stack is a data structure that supports push, pop, top, and getMin() operations, all in O(1) time. The naive approach retrieves the minimum by scanning all elements on each call, resulting in O(N) time for getMin(). The optimized solution uses two stacks: a main stack for all values and an auxiliary min stack that tracks the running minimum at every stage. When a new element is pushed, it is added to the min stack only if it is less than or equal to the current minimum; when popped, it is removed from the min stack if it matches the top. This ensures the top of the min stack always holds the current minimum without any traversal.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in