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:

the StackMin class which keeps the top Element and the current MinElement and implements the three functions: push, pop and min:

class MinStack {
    class Node{
        int val;
        int min;
    }
    
    Stack<Node> st = new Stack<Node>();
    
    public void push(int x) {
        Node node = new Node();
        node.val = x;
        if(st.isEmpty()){
            node.min=x;
        }else{
            Node top = st.peek();
            if(top.min <x){
                node.min=top.min;
            }else{
                node.min=x;
            }
        }
        st.push(node);
    }

    public void pop() {
        st.pop();
    }

    public int top() {
        return st.peek().val;
    }

    public int getMin() {
        return st.peek().min;
    }
}

One Thought on “Min Stack Problem

  1. Shrikant Jadhav on January 29, 2016 at 6:41 pm said:

    Dear Sir/Madam,

    I found this article useful. n I am really grateful to u for that. but I wanted to ask u “can i publish this info on my blog”. so that my friends will get some help too.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation