155. Min Stack

155. Min Stack

[Medium] “Design a stack that supports push, pop, top, and retrieving the minimum element in constant time."

Link to Leetcode

Python3:

class MinStack:

    def __init__(self):
        self.stack = []
        
    def push(self, x: int) -> None:
        if (len(self.stack) == 0) or (x < self.stack[-1][1]):
            stack_min = x
        else:
            stack_min = self.stack[-1][1]
        self.stack.append((x, stack_min))

    def pop(self) -> None:
        self.stack.pop()

    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]