155. Min Stack

Solution

struct Node {
    int min = 0;
    int val = 0;
};

class MinStack {
public:
    vector<Node> stack;
public:
    MinStack() {
        
    }
    
    void push(int val) {
        Node toPush{};
        if (stack.empty()) {
            toPush.min = val;
        } else {
            toPush.min = val < getMin() ? val : getMin();
        }
        toPush.val = val;
        stack.push_back(toPush);
    }
    
    void pop() {
        stack.pop_back();
    }
    
    int top() {
        return stack.back().val;
    }
    
    int getMin() {
        return stack.back().min;
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(val);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->getMin();
 */

Complexity

  • Time Complexity: O(1).
  • Space Complexity: O(2N), where N is the size of inserted elements.

All Solutions