Easy to understand O(n) Java solution with handling of all corner cases.


  • 0
    K

    """

    public List<String> findMissingRanges(int[] nums, int lower, int upper) {
        int n = nums.length;
        List<String> res = new ArrayList<String>();
        
        if (n == 0) {
           res.add(getRange(lower,upper));
            return res;
        }
        
        if (upper > nums[n-1])
            res.add(0,getRange(nums[n-1]+1,upper));
            
        for (int i = n-1; i >= 1; i--) {
            if (nums[i] != nums[i-1] && nums[i] - nums[i-1] != 1)
                res.add(0,getRange(nums[i-1]+1,nums[i]-1));
        }
        
        if (lower < nums[0])    
            res.add(0,getRange(lower,nums[0]-1));
        return res;
    }
    
    public String getRange(int i, int j) {
        return i==j? String.valueOf(i): i +"->"+ j;
    }
    

    """


Log in to reply
 

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