The Min Stack problem requires designing a stack that supports retrieving the minimum element in constant time.

Problem

Design a stack that supports the standard stack operations push, pop, and top, along with a getMin operation that returns the minimum element currently present in the stack.

All operations should run in O(1) time.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
push(-2)
push(0)
push(-3)
getMin()
pop()
top()
getMin()
Output
-3
0
-2

Example 2

Input
push(2)
push(0)
push(3)
push(0)
getMin()
pop()
getMin()
pop()
getMin()
Output
0
0
0

Solution

This solution uses the Stack pattern. We maintain two stacks: one stack stores the actual values, while the second stack stores the minimum value at each level of the stack.

Whenever a value is pushed, we also push the smaller value between the new value and the current minimum onto the minimum stack. Therefore, the top of the minimum stack always represents the minimum value in the entire stack.

When an element is removed, we remove the top element from both stacks. This keeps the two stacks synchronized and allows getMin() to return the minimum in O(1) time.
class MinStack {

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

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

    public void push(int val) {
        stack.push(val);

        if (minStack.isEmpty()) {
            minStack.push(val);
        } else {
            minStack.push(Math.min(val, minStack.peek()));
        }
    }

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

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

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

Complexity

All operations perform a constant number of stack operations, so push, pop, top, and getMin each have O(1) time complexity.

The two stacks store up to n elements, so the extra space complexity is O(n).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion