Question

Formatted question description: https://leetcode.ca/all/155.html

155	Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

@tag-stack

Algorithm

Two stacks are used to achieve this, one stack is used to store the data that push in in order, and the other is used to store the smallest value that has occurred.

Code

Java

class MinStack {

    Stack<Integer> sk = new Stack<>();
    Stack<Integer> min = new Stack<>();
    
    public void push(int x) {
        sk.push(x);
        // @note: if pushing duplicated, then the 2nd is missing if no "="
        if (min.isEmpty() || min.peek() >= x) {
            min.push(x);
        }
    }

    public void pop() {
        int popVal = sk.pop();
        if (popVal == min.peek()) {
            min.pop();
        }
    }

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

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

	
}

class MinStack_SortedList_ACed {

    Stack<Integer> sk;
    PriorityQueue<Integer> sorted;

    /** initialize your data structure here. */
    public MinStack_SortedList_ACed() {
        sk = new Stack<>();
        sorted = new PriorityQueue<>();
    }

    public void push(int x) {
        sk.push(x);
        sorted.offer(x); // NlogN
    }

    public void pop() {
        int popped = sk.pop();

        // remove by object, not by index
        // but, here remove() is o(N) operation
        sorted.remove(popped);
    }

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

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

All Problems

All Solutions