Simple Python Solution with Comments


  • 0
    N
    class Solution(object):
        def findMissingRanges(self, nums, lower, upper):
            """
            :type nums: List[int]
            :type lower: int
            :type upper: int
            :rtype: List[str]
            """
            output = []
            
            #acts as the number to represent the start of the missing range 
            start  = None
            #check if the lower number in the nums array 
            if len(nums)==0 or lower != nums[0]:
                start = lower
                start_index = 0
            else:
                start =  nums[0] + 1
                start_index = 1
                
            for i in range(start_index, len(nums)):
                current_num = nums[i]
                #if one numer between two consecutuve values
                if current_num - 1 == start:
                    output.append(str(start))
                #If more then 1 number in between consecutive values
                elif current_num - 1 > start:
                    output.append("{}->{}".format(str(start), str(current_num-1)))
                    
                #increment start
                start = current_num +1
            
            #chekc if upper is not in nums array meaning upper = start
            if upper == start:
                output.append(str(start))
            elif upper > start:
                output.append("{}->{}".format(str(start), str(upper)))
                
            return output
    

Log in to reply
 

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