Java Solution with explanations


  • 0
    M
     public static List<String> findMissingRanges(int[] nums, int lower, int upper) {
            if(nums.length == 0 || lower == upper)
                return new ArrayList<>();
    
            List<String> ranges = new ArrayList<>();
    
            //Handle first and lower boundary
            if(nums[0] > lower) {
                ranges.add(getRange(lower-1, nums[0]));
            }
    
            //Handle elements in array
            for(int i = 0; i < nums.length -1; i++) {
                //Only add if the difference is > 1 and nums within range
                if(nums[i+1] - nums[i] != 1 && nums[i] >= lower && nums[i+1] <= upper) {
                    ranges.add(getRange(nums[i], nums[i+1]));
                }
            }
    
            //Handle last & upper boundary
             if(nums[nums.length -1] < upper) {
                ranges.add(getRange(nums[nums.length-1], upper+1));
            }
    
            return ranges;
        }
    
        private static String getRange(int num1, int num2) {
            if(num2 - num1 == 2) {
                return num1 + (num2 - num1 - 1) + "";
            } else {
                return (num1 + 1) + "->" + (num2 - 1);
            }
        }
    
        public static void main(String[] args) {
          //Tests      
          findMissingRanges(new int[] {2,7,9}, 0, 10); //0->1, 3->6, 8, 10
          findMissingRanges(new int[] {1}, 0, 10); //0, 2->10
          findMissingRanges(new int[] {1,10}, 0, 10); // 0, 2->9
          findMissingRanges(new int[] {0}, 0, 10); // 1->10
        }
    

    Note: I DO NOT have subscription, hence I cannot submit.
    I have tried my best with many individual test cases. I hope you find this useful.


Log in to reply
 

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