228. Summary Ranges

# Medium

Key idea: three veriables, start point of range, end point of range, current point.

Compare current number to the last one.

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        res = []
        # edge case
        if len(nums) == 0:
            return []
        elif len(nums) == 1:
            res.append(str(nums[0]))
            return res
        
        left = 0
        right = 0
        i = 1
        while i < len(nums):
            if nums[i] == nums[right] + 1:
                right += 1
                i += 1
                continue
            # if find the range
            if left == right:
                res.append(str(nums[left]))
            else:
                tmp = str(nums[left]) + "->" + str(nums[right])
                res.append(tmp)
            left = i
            right = i
            i += 1
            
        if left == right:
            res.append(str(nums[left]))
        else:
            tmp = str(nums[left]) + "->" + str(nums[right])
            res.append(tmp)
        return res

Last updated