155. Min Stack

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

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • int getMin() retrieves the minimum element in the stack.

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


class MinStack:
   
    def __init__(self):
        self.minTrace = []
        self.minStack = []

    def push(self, val: int):
        self.minStack.append(val)
        if not self.minTrace or val < self.minTrace[-1]:
            self.minTrace.append(val)
        else:
            self.minTrace.append(self.minTrace[-1])

    def pop(self):
        self.minStack.pop()
        self.minTrace.pop()

    def top(self):
        return self.minStack[-1]

    def getMin(self):
        return self.minTrace[-1]

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break