This is from leetcode question 155. Min Stack
The getMin() function returns incorrect answer in a particular testcase and i don’t understand why!
class MinStack {
static ArrayList<Integer> stack = new ArrayList<Integer>();
static ArrayList<Integer> minStack = new ArrayList<Integer>();
public MinStack() {
}
public void push(int val) {
stack.add(val);
if (minStack.isEmpty() || val <= minStack.get(minStack.size() - 1)) {
minStack.add(val);
}
}
public void pop() {
if (stack.isEmpty()) {
return;
}
int removed = stack.remove(stack.size() - 1);
if (removed == minStack.get(minStack.size() - 1)) {
minStack.remove(minStack.size() - 1);
}
}
public int top() {
if (stack.isEmpty()) {
return 0;
}
return stack.get(stack.size() - 1);
}
public int getMin() {
return minStack.get(minStack.size() - 1);
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
Here is the testcase result –>
getMin() returns -2 instead of -1
New contributor
Rakshit Golhar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.