C++ 6 lines solution beat all

  • 3

    do not remember where did i steal the idea, but this is super brilliant.
    the data structure use a int pair to store top and current min element

    if the top is current min, when we do pop operation, we also updated the current min

    class MinStack {
        /** initialize your data structure here. */
        MinStack() {
        void push(int x) {
            if(stk.empty()) stk.push(make_pair(x,x));
            else stk.push(make_pair(x,min(x,stk.top().second)));
        void pop() {
        int top() {
            return stk.top().first;
        int getMin() {
            return stk.top().second;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.