I was attempting a question on leetcode and not sure about this anomalous behaviour. I am providing the logic part of the question. Please let me know if any discrepancy is found.
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.
Approach: Using 2 stacks, values
(with original values in their order) and min
(with values sorted in ascending order)
class MinStack {
Stack<Integer> min;
Stack<Integer> values;
/** initialize your data structure here. */
public MinStack() {
min = new Stack<>();
values = new Stack<>();
}
public void push(int x) {
if(values.isEmpty()){
values.push(x);
min.push(x);
}
else{
values.push(x);
if(min.peek()<x){
List<Integer> list = new ArrayList<>();
while(!min.isEmpty() && min.peek()<x)
list.add(min.pop());
min.push(x);
for(int i=list.size()-1;i>=0;i--)
min.push(list.get(i));
}
else
min.push(x);
}
System.out.println("min after push-->"+min);
System.out.println("values after push -->"+values);
}
public void pop() {
if(values.peek()==min.peek()){
min.pop();
}
else{
List<Integer> list = new ArrayList<>();
while(!min.isEmpty() && min.peek()!=values.peek()){
list.add(min.pop());
}
if(!min.isEmpty()){
min.pop();
}
for(int i=list.size()-1;i>=0;i--)
min.push(list.get(i));
}
values.pop();
System.out.println("min after pop -->"+min);
System.out.println("values after pop-->"+values);
}
public int top() {
System.out.println("min on top -->"+min);
System.out.println("values on top-->"+values);
return values.peek();
}
public int getMin() {
System.out.println("min for getMin-->"+min);
System.out.println("values for get min-->"+values);
return min.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/