Design a Stack with Constant-Time Minimum Retrieval

DSA Medium 29 views
Back to Questions

Problem Description

Design a stack data structure that supports standard stack operations such as push, pop, and top, along with an additional operation getMin() that returns the minimum element present in the stack at any time, all in O(1) time. Explain how auxiliary data structures help achieve this efficiency.

Solutions (1)

DSA
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() || val <= minStack.peek()) {
            minStack.push(val);
        } else {
            minStack.push(minStack.peek());
        }
    }
    
    public void pop() {
        if (!stack.isEmpty()) {
            stack.pop();
            minStack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

// One stack solution
class MinStack2 {
    private Stack<Integer> stack;
    private int min;
    
    public MinStack2() {
        stack = new Stack<>();
        min = Integer.MAX_VALUE;
    }
    
    public void push(int val) {
        if (val <= min) {
            stack.push(min);
            min = val;
        }
        stack.push(val);
    }
    
    public void pop() {
        if (stack.pop() == min) {
            min = stack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min;
    }
}
1 likes 0 comments

Discussion (0)

No comments yet. Start the discussion!

Prev Next