Skip to content

Instantly share code, notes, and snippets.

@nealhu
Created July 3, 2014 03:02
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 nealhu/9fd25a583db13d4e7647 to your computer and use it in GitHub Desktop.
Save nealhu/9fd25a583db13d4e7647 to your computer and use it in GitHub Desktop.
CC_3_2
// Cracking the Coding Interview
// 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;
class MinStack {
private Stack<Integer> s;
private Stack<Integer> minValues;
public MinStack() {
s = new Stack<Integer>();
minValues = new Stack<Integer>();
}
public void push(Integer element) {
s.push(element);
if (minValues.empty() || element <= minValues.peek()) {
minValues.push(element);
}
s.push(element);
}
public Integer pop() {
if (minValues.peek() < s.peek()) {
return s.pop();
} else {
minValues.pop();
return s.pop();
}
}
public Integer min() {
return minValues.peek();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment