Tuesday, January 13, 2015

Min Stack (LeetCode Data Structure)

Question: 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.

Idea: Use two stacks. One stack (valStack) is a normal stack to store the values. The other stack (minStack) only pushes the minimum values until now and only pops if the popped value from valStack equals the top of the minStack.
For example: input 5, 3,9, 1, 1, 2
Push:
valStack:   5,  3,   9,            1, 1, 2
minStack:  5,  3,  not push, 1, 1, not push
Pop:
valStack:            2,  1,  1,  9,     3,  5
minStack:not pop,   1,  1, not,   3,  5
So we can see the minStack pushes only if the new input is smaller than its top and only pops if the value popped from the valStack equals the top of the minStack.

Time: O(1) Space: O(n) (we used an extra stack)

Code:
 class MinStack {  
   Stack<Integer> minStack=new Stack<Integer>();  
   Stack<Integer> valStack=new Stack<Integer>();  
   public void push(int x) {  
     if(minStack.isEmpty()||x<=minStack.peek())  
       minStack.push(x);  
     valStack.push(x);  
   }  
   public void pop() {  
     if(valStack.isEmpty())  
       return;  
     int val=valStack.pop();  
     if(val==minStack.peek())  
       minStack.pop();  
   }  
   public int top() {  
     if(valStack.isEmpty())  
       return -1;  
     return valStack.peek();  
   }  
   public int getMin() {  
     if(minStack.isEmpty())  
       return Integer.MAX_VALUE;  
     return minStack.peek();  
   }  
 }  

No comments:

Post a Comment