Subtle overflow bug in the judge code


  • 2
    R

    Input:
    [-2147483648, 2147483647] -2147483648 2147483647

    Those are Integer.MIN_VALUE and Integer.MAX_VALUE

    Expected output: ["-2147483647->2147483646"]

    Judge output: []

    I think this code adresses the issue, but is way less elegant as a result:

    public class Solution {
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            if (nums == null || nums.length == 0) return Collections.singletonList(range(lower, upper));
    
            List<String> result = new ArrayList<>();
    
            if (nums[0] > lower) result.add(range(lower, nums[0] - 1));
            int prev = nums[0];
            for (int i = 1; i < nums.length; i++) {
                int v = nums[i];
                if (v == prev) continue;
                if (v - 1 > prev) result.add(range(prev + 1, v - 1));
                prev = v;
            }
            if (prev < upper) result.add(range(prev + 1, upper));
    
            return result;
        }
    
        private String range(int l, int r) {
            return l == r
                    ? Integer.toString(l)
                    : l + "->" + r;
        }
    }

  • 0
    R

    Oh, and for those participating in TopCoder, and alike, how often do you have to worry about such edge cases?


  • 0

    @roedeer42 Thanks, this is fixed and I have added your test case.


Log in to reply
 

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