August 27, 2019

155. Min Stack

155. Min Stack

Basic Solution using Two Stacks

Time=O(1), space=(n)

Stack: 5 5 6 6 7 7 2 2
minStack: 5 5 5 5 5 5 2 2

class MinStack {
    
    Deque<Integer> stack;
    Deque<Integer> minStack;

    /** initialize your data structure here. */
    public MinStack() {
        stack = new ArrayDeque<>();
        minStack = new ArrayDeque<>();
    }
    
    public void push(int x) {
        stack.push(x);
        if (!minStack.isEmpty() && minStack.peek() < x) {
            minStack.push(minStack.peek());
        } else {
            minStack.push(x);
        }
    }
    
    public void pop() {
        if (!stack.isEmpty()) {
            stack.poll();
            minStack.poll();            
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

Optimized Solution using Two Stacks

Optimized usage of stack 2 (assuming there are lots of duplicates).

Time=O(1), space=(n)

Stack: 5 5 6 6 7 7 2 2
minStack: 5 5 2 2

class MinStack {
    
    Deque<Integer> stack;
    Deque<Integer> minStack;

    /** initialize your data structure here. */
    public MinStack() {
        stack = new ArrayDeque<>();
        minStack = new ArrayDeque<>();
    }
    
    public void push(int x) {
        stack.push(x);
        // when value <= current min value in stack, need to push the value to minStack
        if (minStack.isEmpty() || minStack.peek() >= x) {
            minStack.push(x);
        }
    }
    
    public void pop() {
        int x = stack.pop();
        // When the popped value is the same as top value of minStack, 
        // the value need to be popped from minStack
        if (x == 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(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

Optimized Solution with One Stack

TODO

comments powered by Disqus