Extremely weird. Maybe a LeetCode Bug.(Solved)


  • 0
    Z

    Notice that I substituted min.peek() with getMin(), and then the code got accepted. However, these two statements are equivalent. I am totally confused with this result.

    The following is wrong answer code. It fails at:

    Input:
    push(512),push(-1024),push(-1024),push(512),pop,getMin,pop,getMin,pop,getMin

    Output: [-1024,-1024,-1024]

    Expected: [-1024,-1024,512]

    public class MinStack {
        
        Deque<Integer> stack = new LinkedList<>();
        Deque<Integer> min = new LinkedList<>();
        
        public void push(int x) {
            stack.push(x);
            if(min.isEmpty() || x <= min.peek()) min.push(x);
        }
    
        public void pop() {
            if(min.peek() == stack.pop()) min.pop();
        }
    
        public int top() {
            return stack.peek();
        }
    
        public int getMin() {
            return min.peek();
        }
    }
    

    However, if I do this:

    public class MinStack {
        
        Deque<Integer> stack = new LinkedList<>();
        Deque<Integer> min = new LinkedList<>();
        
        public void push(int x) {
            stack.push(x);
            if(min.isEmpty() || x <= getMin()) min.push(x);
        }
    
        public void pop() {
            if(getMin() == stack.pop()) min.pop();
        }
    
        public int top() {
            return stack.peek();
        }
    
        public int getMin() {
            return min.peek();
        }
    }
    

    The code get accepted. Weird isn't it?


  • 0

    They're not equivalent. Calling getMin() converts the Integer to an int, which min.peek() doesn't.


  • 0
    Z

    Yes, I got your idea. But it seems in the test case, pop() and peek() is never called when stack is empty. As a result, the Integer value will not be null. Comparing Integer with Integer in such case is equivalent to comparing Integer with int.


  • 0
    Z

    I got it. Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.