algoadvance

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

You must implement a solution with O(1) time complexity for each function.

Clarifying Questions

  1. Are there any constraints on the values that can be pushed onto the stack?
    • No, the problem does not specify any constraints on the values.
  2. Is there any limit to the size of the stack?
    • No, the problem does not specify any size limits for the stack.
  3. What should be the behavior if pop or top is called on an empty stack?
    • Since this is a typical interview question, we can assume the stack is not empty when pop or top is called. Otherwise, we may need to handle exceptions or errors appropriately.

Strategy

To keep track of the minimum element in constant time, we can use an auxiliary stack that maintains the current minimum elements. Here’s how we can design the MinStack:

By doing this, we ensure that all operations run in constant time, O(1).

Code

class MinStack:
    def __init__(self):
        self.main_stack = []
        self.min_stack = []

    def push(self, val: int) -> None:
        self.main_stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]:
            self.min_stack.append(val)

    def pop(self) -> None:
        if self.main_stack:
            top_value = self.main_stack.pop()
            if top_value == self.min_stack[-1]:
                self.min_stack.pop()

    def top(self) -> int:
        if self.main_stack:
            return self.main_stack[-1]
        return None # Should not happen, as per our assumptions.

    def getMin(self) -> int:
        if self.min_stack:
            return self.min_stack[-1]
        return None # Should not happen, as per our assumptions.

Time Complexity

This design ensures that all required operations are performed in constant time, meeting the problem’s requirements.

Try our interview co-pilot at AlgoAdvance.com