Python solution with detailed explanation

  • 0


    Summary Ranges


    1. The problem is simple but has corner cases.
    2. While printing a range, if start and end are same, then you dont need "->".
    3. Your entire list can complete out and the last range might get missed.
    class Solution(object):
        def write_result(self, start, end, summary, nums):
            result = "%s->%s"%(nums[start], nums[end]) if start != end else "%s"%(nums[start])
        def summaryRanges(self, nums):
            :type nums: List[int]
            :rtype: List[str]
            if nums == []:
                return []
            summary, s, e = [], 0, 1
            while e < len(nums):
                if nums[e] != nums[e-1]+1:
                    self.write_result(s, e-1, summary, nums)
                    s = e
                e += 1
            self.write_result(s, e-1, summary, nums)
            return summary

Log in to reply

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