C++ easy sol with vector and helper min stack


#1
vector<int> stack_min; // container for stack
stack<int> min_ix_s; //keep ixs for all mins

MinStack::MinStack() {
    stack_min.clear();
    while (!min_ix_s.empty()) min_ix_s.pop();
}

void MinStack::push(int x) {
    if (stack_min.empty())
    {
        min_ix_s.push(0);
    }
    else if (x < getMin())// add new min ix to stack
    {
        min_ix_s.push(stack_min.size());
    }
    stack_min.push_back(x);
}

void MinStack::pop() {

    if (stack_min.empty()) return;

    stack_min.erase(--stack_min.end());

    if (min_ix_s.top() == stack_min.size()) //min changed, find new one
    {
        min_ix_s.pop();
    }

}

int MinStack::top() {
    if (stack_min.empty()) return -1;

    return *(--stack_min.end());
}

int MinStack::getMin() {
    if (stack_min.empty()) return -1;
    int res = stack_min[min_ix_s.top()];
    return res;
}