Post

Leetcode 155. Min Stack

Explanation for Leetcode 155 - Min Stack, and its solution in Python.

Problem

Leetcode 155 - Min Stack

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

Approach

We can use 2 stack to keep track of min value.

  • One stack where it just operates just like stack
  • Other stack where it keeps track of min values from stack. We can push the value by comparing the top of minStack

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MinStack:
    def __init__(self):
        self.arr = []
        self.minStack = []

    def push(self, val: int) -> None:
        self.arr.append(val)
        minVal = min(val, self.minStack[-1] if self.minStack else val)
        self.minStack.append(minVal)
    
    def pop(self) -> None:
        self.arr.pop()
        self.minStack.pop()

    def top(self) -> int:
        return self.arr[-1]
    
    def getMin(self) -> int:
        return self.minStack[-1]

Time Complexity and Space Complexity

Time Complexity: $O(1)$ for all operations

Space Complexity: $O(n)$

This post is licensed under CC BY 4.0 by the author.