LeetCode Solutions

155. Min Stack

Time: $O(1)$

Space: $O(n)$

			

class MinStack {
 public:
  void push(int x) {
    if (stack.empty())
      stack.emplace(x, x);
    else
      stack.emplace(x, min(x, stack.top().second));
  }

  void pop() {
    stack.pop();
  }

  int top() {
    return stack.top().first;
  }

  int getMin() {
    return stack.top().second;
  }

 private:
  stack<pair<int, int>> stack;  // {x, min}
};
			

class MinStack {
  public void push(int x) {
    if (stack.isEmpty())
      stack.push(new int[] {x, x});
    else
      stack.push(new int[] {x, Math.min(x, stack.peek()[1])});
  }

  public void pop() {
    stack.pop();
  }

  public int top() {
    return stack.peek()[0];
  }

  public int getMin() {
    return stack.peek()[1];
  }

  private Stack<int[]> stack = new Stack<>(); // {x, min}
}
			

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

  def push(self, x: int) -> None:
    mini = x if not self.stack else min(self.stack[-1][1], x)
    self.stack.append([x, mini])

  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]