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

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 stack;
    Stack 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();
 */
Total
0
Shares
Leave a Reply

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

Previous Post

How Much Does It Cost to Create an App in 2026?

Next Post

AI engine optimization audit: How to audit your content for AI search engines

Related Posts