Search code examples
javadata-structuresstack

stack1.peek() == stack2.peek() return false with the same elements in both stack in java


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();
 */

Solution

  • 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]