Both the exercise on stacks have bugs, not scalable and with limitation. For a beginner like me, after doing it myself and not be able to find the correct solution, I will go check Mosh solution and try to analyze how to solve it.
For example in minStack exercise.
While testing around the logic with command below:
var stacks = new MinStack();
stacks.push(8);
stacks.push(1);
stacks.push(2);
stacks.push(3);
stacks.push(5);
stacks.push(1);
stacks.pop();
var x = stacks.min();
System.out.println(x);
public class MinStack {
private Stack stack = new Stack<>();
private Stack minStack = new Stack<>();
public void push(int item) {
stack.push(item);
if (minStack.isEmpty())
minStack.push(item);
else if (item < minStack.peek())
minStack.push(item);
}
public int pop(){
var top = stack.pop();
if ( minStack.peek() == top )
minStack.pop();
return top;
}
public int min() {
return minStack.peek();
}
}
problem is that, after adding 1(the least) after pushing 8. Since 1 is less than any other element pushed. The next minimum value would be 8. Thus if you push 1 as duplicate and pop it out. You only have one value left on stack which is 8 and that’s going to be your minimum regardless of the value of others.