DEV Community

Debesh P.
Debesh P.

Posted on

155. Min Stack | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/min-stack/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/min-stack/solutions/7568000/most-optimal-code-beats-200-all-language-2flu


leetcode 155


Solution

class MinStack {

    Stack<Integer> stack;
    Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        if(minStack.isEmpty() || val <= minStack.peek()) {
            minStack.push(val);
        }
    }

    public void pop() {
        int poppedVal = stack.pop();
        if(poppedVal == minStack.peek()) {
            minStack.pop();
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
Enter fullscreen mode Exit fullscreen mode

Top comments (0)