Java Solution O(n) runtime


  • 0
    C
        public List<String> findMissingRanges(int[] nums, int lower, int upper) {
            // minus 1 as we always pre increment count
            int count = lower - 1;
    
            List<String> result = new ArrayList<String>();
            for(int i=0; i<nums.length; i++){
                if(++count != nums[i]){
                    result.add(createMissingRange(count, nums[i]));
                    count = nums[i];
                }
            }
            
            if(count < upper){
                // adding 1 to upper as createMissingRange, end is exclusive
                result.add(createMissingRange(count + 1, upper + 1));
            }
            
            return result;
        }
        
        private String createMissingRange(int i, int j){
            StringBuilder sb = new StringBuilder();
            sb.append(i);
            
            if(i + 1 != j){
                sb.append("->").append(j - 1);
            }
            
            return sb.toString();
        }
    

Log in to reply
 

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