0

I was solving the leetcode problem (link:https://leetcode.com/problems/min-stack/) by making two stacks, but in the pop function if I compare s.peek() == ss.peek() if statement does not execute why?

class MinStack {
        Stack <Integer> s = new Stack<>();
        Stack <Integer> ss = new Stack<>();
        
    public MinStack() {
       
    }
    
    public void push(int val) {
        if(ss.isEmpty() || val<=ss.peek()) ss.push(val);
        s.push(val);
        return;
    }
    
    public void pop() {
        if(s.isEmpty()) return;
        int a = s.peek();
        int b = ss.peek();
        
        if(s.peek() == ss.peek(){
        //this does not work
            ss.pop();
        }

        if(a == b){
            ss.pop();
        }
        s.pop();
        return;
    }
    
    public int top() {
        if(s.isEmpty()) return -1;
        return s.peek();
    }
    
    public int getMin() {
        if(ss.isEmpty()) return -1;
        return ss.peek();
    }
}
/**
 * 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();
 */
  • 2
    Your stack stores not `int` values but `Integer` values. Since `Integer` values are objects you must use `.equals()` to compare them. – Thomas Kläger Jun 27 '22 at 05:57

1 Answers1

0

Comparison will only work for values between -128 and 127

This snippet will return true

Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
s1.push(127);
s2.push(127);
System.out.println(s1.peek() == s2.peek());

Whereas, this will return false

Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
s1.push(128);
s2.push(128);
System.out.println(s1.peek() == s2.peek());

Use s1.peek().equals(s2.peek()) for values outside range [-128,127]

  • And the comparison will only work if those values between -128 and 127 were both boxed using auto-boxing or `Integer.valueOf(..)`. If one or both were created with `new Integer(...)`, they will also not compare equal. In other words, you should **always** use `equals`. – Mark Rotteveel Jun 27 '22 at 06:56