DEV Community

Tanuja V
Tanuja V

Posted on

2 1

Min Stack | LeetCode | Java

class MinStack {

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

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

    public void push(int val) {
        int min = val;

        if(!minStack.isEmpty() && minStack.peek()<min)
            min = minStack.peek();

        stack.push(val);
        minStack.push(min);

    }

    public void pop() {
        stack.pop();
        minStack.pop();
    }

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

    public int getMin() {
        return minStack.peek();
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (2)

Collapse
 
sehgalspandan profile image
Spandan Sehgal β€’

Hi @tanujav πŸ™ƒ , just a recommendation from my side (from a reader's pov): It would be better if you could explain the terms like "Min Stack" with examples and also explain what your code does step by step.

Keep up the good work πŸŽ‰
All the best ✨

Collapse
 
tanujav profile image
Tanuja V β€’

Thanks for the input, Spandan
I will definitely take this into account from upcoming posts :)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more