Java solution with just one stack

  • 0

    This approach is pushing the min of the stack after every push methods. And retrieve the min after pop.

    public class MinStack {
        Stack<Integer> stack;
        int min;
        /** initialize your data structure here. */
        public MinStack() {
            min = Integer.MAX_VALUE;
            stack = new Stack<Integer>();
        public void push(int x) {
            min = Math.min(min, x);
        public void pop() {
            min = stack.isEmpty() ? Integer.MAX_VALUE : stack.peek();
        public int top() {
            int temp = stack.pop();
            int res = stack.peek();
            return res;
        public int getMin() {
            return stack.peek();

Log in to reply

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