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.


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

    /** initialize your data structure here. */
    .search(Object o): Returns the 1-based position where an object is on this stack.
    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 .empty() is for Stack, .isEmpty() is inhereted from Vector.
        if (min.empty()) {
            // Should use .peek()
        } else if (x <= min.peek()) {

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


    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();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s