Tuesday, December 9, 2014

Min Stack

Q:
 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.

T:
We need another stack to store the current minimum element. We can push the current minimum element into that stack when pushing data to the stack. To improve this a little bit, we don't need to push the current minimum each time we push a new data. We only need to push a new minimum value if we see a new value, which is less or equal to current minimum. When poping, we only pop the current minimum element when we pop the same value from the data stack.

A:

class MinStack {
public:
    stack data;
    stack minstack;
    void push(int x) {
        data.push(x);
        if(minstack.empty() || minstack.top() >= x) {
            minstack.push(x);
        }
    }

    void pop() {
        if(data.empty()) {
            return;
        }
        int x = data.top();
        data.pop();
        if(x == minstack.top()) {
            minstack.pop();
        }
    }

    int top() {
        if(data.empty()) {
            return -1;
        }
        return data.top();
    }

    int getMin() {
        if (minstack.empty()) {
            return -1;
        }
        return minstack.top();
    }
};

No comments:

Post a Comment