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

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        n = len(nums)
        res = []
        i = 0
        while i < n:
            curr = nums[i]
            while i+1 < n and nums[i] == nums[i+1]-1:
                i+=1
            if curr != nums[i]:
                res.append(str(curr) +"->" + str(nums[i]))
            else:
                res.append(str(curr))
            i+=1
        return res

Last updated

Was this helpful?