228. Summary Ranges

https://leetcode.com/problems/summary-ranges/

Intuitive Solution O(N):

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        n = len(nums)
        start=end="#"
        res = []
        for i in range(n):
            if i == 0 or nums[i] != nums[i-1]+1:
                if start == end:
                    res.append(str(start))
                else:
                    res.append(str(start) + "->" + str(end))
                start = end = nums[i]
            else:
                end = nums[i]
        if start == end:
            res.append(str(start))
        else:
            res.append(str(start) + "->" + str(end))
        return res[1:]

Simplified Solution:

Use while loop

Last updated