Skip to content

Instantly share code, notes, and snippets.

@jason51122
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 jason51122/60751e16fd55a162bf8b to your computer and use it in GitHub Desktop.
Save jason51122/60751e16fd55a162bf8b 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.
import java.util.Stack;
@SuppressWarnings("serial")
public class MinStack extends Stack<Integer> {
private Stack<Integer> minStack;
public MinStack() {
minStack = new Stack<Integer>();
}
public void push(int val) {
super.push(val);
if (val <= min()) {
minStack.push(val);
}
}
// Must return Integer type.
public Integer pop() {
int val = super.pop();
if (val == minStack.peek()) {
minStack.pop();
}
return val;
}
public int min() {
if (super.empty()) {
return Integer.MAX_VALUE;
}
else {
return minStack.peek();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment