155. Min Stack - cocoder39/coco39_LC GitHub Wiki

155. Min Stack

  1. whenever push a value, also calculate what's the min value at this point and push the min value along with the input value
  2. optimization: use an additional stack min_stk to record min value. only push or pop min value when necessary
class MinStack:

    def __init__(self):
        self.stack = []
        self.min_stk = []
        

    def push(self, val: int) -> None:

        self.stack.append(val)
        if not self.min_stk or val <= self.min_stk[-1]:
            self.min_stk.append(val)

    def pop(self) -> None:
        val = self.stack.pop()
        if val == self.min_stk[-1]:
            self.min_stk.pop()
        

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

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

Your MinStack object will be instantiated and called as such:

obj = MinStack()

obj.push(val)

obj.pop()

param_3 = obj.top()

param_4 = obj.getMin()

================================

initial idea: use one more stack to track the min value whenever pushing a new data into the data stack

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        data.push(x);
        int m = min.empty() || min.top() >= x ? x : min.top(); 
        min.push(m);
    }
    
    void pop() {
        data.pop();
        min.pop();
    }
    
    int top() {
        return data.top();
    }
    
    int getMin() {
        return min.top();
    }
private:
    stack<int> data, min;
};

optimization: updating min stack when necessary

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        data.push(x);
        if (min.empty() || min.top() >= x)  min.push(x);
    }
    
    void pop() {
        int tmp = data.top();
        data.pop();
        if (min.top() == tmp)   min.pop();
    }
    
    int top() {
        return data.top();
    }
    
    int getMin() {
        return min.top();
    }
private:
    stack<int> data, min;
};

follow up: design a min queue:

solution 1: implement min queue with min stack solution 2: monotonic queue

⚠️ **GitHub.com Fallback** ⚠️