Fastest Solution so far in Python (40 ms)


  • 0
    A
        #Empty list where we store result
        ret_list= []
        
        #If nums list is empty we only return range between upper and lower
        if(not nums):
            if(upper != lower):
                temp = [str(lower), '->', str(upper)]
                ret_list.append(''.join(temp))
            else:
                ret_list.append(str(upper))    
            return ret_list
        
        # Check to see if our non-empty list is within range of lower and max
        if(nums[-1] < lower or nums[0] > upper):
            return ret_list
        
        # Check for missing range: lower -> first elem of nums
        if(nums[0] - lower > 0):
            if(nums[0] - lower == 1):
                ret_list.append(str(lower))
            else:
                temp = [str(lower), '->', str(nums[0] - 1)]
                ret_list.append(''.join(temp))
            
        # Check for missing ranges between first and last elem of nums list
        for i,num in enumerate(nums):
            if(i + 1 < len(nums) and nums[i+1] - nums[i] <= 1):
                continue
            elif(i + 1 < len(nums) and nums[i+1] - nums[i] == 2):
                ret_list.append(str(nums[i] + 1))
            elif(i + 1 < len(nums) and nums[i+1] - nums[i] > 2):
                temp = [str(nums[i] +1), '->', str(nums[i+1]-1)]
                ret_list.append(''.join(temp))
                
        # Check for missing range: last elem of nums -> upper
        if(upper - nums[-1] > 0):
            if(upper - nums[-1] == 1):
                ret_list.append(str(upper))
            else:
                temp = [str(nums[-1] +1), '->', str(upper)]
                ret_list.append(''.join(temp))
        
        return ret_list

Log in to reply
 

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