Skip to content

Instantly share code, notes, and snippets.

@JoyceeLee
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoyceeLee/9fdc6b744d63b0238b3a to your computer and use it in GitHub Desktop.
Save JoyceeLee/9fdc6b744d63b0238b3a to your computer and use it in GitHub Desktop.
/*3.2 How would you design a stack which, in addition to push and pop,
also has a function min which returns the minimum element?
Push, pop and min should all operate in O(1) time.*/
public class Solution extends Stack<Integer> {
Stack<Integer> minSt;
public Solution {
minSt = new Stack<Integer>();
}
public void push(int v) {
if(value<=min()) {
minSt.push(v);
}
super.push(v);
}
public Integer pop() {
int v = super.pop();
if(v==min()) {
minSt.pop();
}
return v;
}
public int min() {
if(minSt.isEmpty()) {
return Integer.MAX_VALUE;
} else {
return minSt.peek();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment