Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Min Stack - Solution/C++

155. Min Stack

Question:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack.

Example:

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

Constraints:
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • Source code:

    Version 1

    Idea:
    Retrieving the minimum element is a key point, only one Stack can't handle this, because Stack are a type of container adpators with Last In First Out(LIFO).

    So, we need to declare two Stack variables.
    In the push() function, st can be added directly. Howerver, min_st must be checked whether the size of min_st is empty or a top of value of min_st is bigger than input value. If the IF statement is true, added input value to min_st.

    In the pop() function, we can't pop any value in min_st. We should check a value of st.pop() whether it's equal to min_st.pop().

    Finally, we can get the minimum element by using getMin() function.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    class MinStack {
    public:
    /** initialize your data structure here. */
    stack<int> st;
    stack<int> min_st;

    MinStack() {
    }

    void push(int x) {
    st.push(x);
    if(min_st.empty() || min_st.top() >= x) min_st.push(x);
    }

    void pop() {
    if(min_st.top() == st.top()) min_st.pop();
    st.pop();
    }

    int top() {
    return st.top();
    }

    int getMin() {
    return min_st.top();
    }
    };

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