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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.
public class MinStack {
        Stack<Integer> stack;
        Stack<Integer> min;

    /** initialize your data structure here. */
    /*
    .empty()
    .pop()
    .peek()
    .push()
    .search(Object o): Returns the 1-based position where an object is on this stack.
    Vector:
    add, add, addAll, addAll, addElement, capacity, clear, clone, contains, containsAll, copyInto, elementAt, elements, ensureCapacity, equals, firstElement, get, hashCode, indexOf, indexOf, insertElementAt, isEmpty, iterator, lastElement, lastIndexOf, lastIndexOf, listIterator, listIterator, remove, remove, removeAll, removeAllElements, removeElement, removeElementAt, removeRange, retainAll, set, setElementAt, setSize, size, subList, toArray, toArray, toString, trimToSize
    */
    public MinStack() {
        stack = new Stack<>();
        min = new Stack<>();
    }

    public void push(int x) {
        stack.push(x);
        // Stack .empty() is for Stack, .isEmpty() is inhereted from Vector.
        if (min.empty()) {
            min.push(x);
            // Should use .peek()
        } else if (x <= min.peek()) {
            min.push(x);
        }
    }

    public void pop() {
        if (stack == null) {
            return;
        }
        // min.peek() == stack.peek() is not working, because they are not pointing to the same location.
        if (min.peek().equals(stack.peek())) {
            min.pop();
        }
        stack.pop();

    }

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

    public int getMin() {
        return min.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();
 */
Advertisements