Saturday, April 11, 2015

Min Stack

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


Solution:
class MinStack {
private:
    stack<int> istack;
    stack<int> min_stack; // Creating an equal size additional stack. Could be done by just storing minimum element once.
public:
    void push(int x) {
        if (min_stack.empty() || x <= min_stack.top()) {
            min_stack.push(x);
        } else {
            min_stack.push(min_stack.top());
        }
        istack.push(x);
    }

    void pop() {
        if (!istack.empty()) {
            istack.pop();
            min_stack.pop();
        }
    }

    int top() {
        int elem;
        if (!istack.empty()) {
            elem = istack.top();
        }
        return elem;
    }

    int getMin() {
        int elem;
        if (!min_stack.empty()) {
            elem = min_stack.top();
        }
        return elem;
    }
};

No comments:

Post a Comment