Final answer:
To design a stack with O(1) lookup time for the minimum element, you can use an additional stack called 'minStack'.
Step-by-step explanation:
To design a stack with O(1) lookup time for the minimum element, we can use an additional stack to keep track of the minimum element. We will call this stack the 'minStack.' Here is an implementation of the MinStack class:
- Create two stacks: 'stack' and 'minStack.'
- When pushing an element 'val' onto the stack, push 'val' onto the 'stack' and check if 'val' is smaller than or equal to the current minimum element in 'minStack.' If it is, push 'val' onto 'minStack' as well.
- When popping an element from the stack, pop it from 'stack' and check if the popped element is equal to the top element of 'minStack.' If it is, pop the top element from 'minStack' as well.
- When getting the top element of the stack, simply return the top element of 'stack.'
- When retrieving the minimum element, return the top element of 'minStack.'