Home > Software design >  LeetCode 155. Min Stack
LeetCode 155. Min Stack

Time:12-27

I am trying to solve the problem using extra space. In the pop() function, when I compare the top of both the stacks inside the if condition, the following test case is failing: ["MinStack","push","push","push","push","pop","getMin","pop","getMin","pop","getMin"]\ [[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]

When I store the top of the first stack and then compare it with the top of the second stack, all the test cases pass.

Can someone please help me understand what is causing this?

The below code caused the test case to fail.

class MinStack {

    Stack<Integer> s;
    Stack<Integer> auxStack;

    public MinStack() {
        s = new Stack<Integer>();
        auxStack = new Stack<Integer>();
    }
    
    public void push(int val) {
        this.s.push(val);
        if (this.auxStack.empty() || val <= this.auxStack.peek()) {
            this.auxStack.push(val);
        }
    }
    
    public void pop() {
        if (this.s.peek() == this.auxStack.peek()) {
            this.auxStack.pop();
        }
        this.s.pop();
    }
    
    public int top() {
        return this.s.peek();
    }
    
    public int getMin() {
        return this.auxStack.peek();
    }
}

The below code worked for all the test cases.

class MinStack {

    Stack<Integer> s;
    Stack<Integer> auxStack;

    public MinStack() {
        s = new Stack<Integer>();
        auxStack = new Stack<Integer>();
    }
    
    public void push(int val) {
        this.s.push(val);
        if (this.auxStack.empty() || val <= this.auxStack.peek()) {
            this.auxStack.push(val);
        }
    }
    
    public void pop() {
        int ans = this.s.pop();
        if (ans == this.auxStack.peek()) {
            this.auxStack.pop();
        }
    }
    
    public int top() {
        return this.s.peek();
    }
    
    public int getMin() {
        return this.auxStack.peek();
    }
}

CodePudding user response:

The problem is that you are comparing Integer objects, not int values. The data type stored on the stack is Integer. So the peek() method returns an Integer, not int, which means that the following comparison is always false:

this.s.peek() == this.auxStack.peek()

Fix this by explicitly converting at least one of those two Integer objects to an int:

this.s.peek().intValue() == this.auxStack.peek()

Or use the equals method:

this.s.peek().equals(this.auxStack.peek())
  • Related