7-line Python implementation

  • 7

    Thoughts are simple O(n) solution, just share my implementation!

    def summaryRanges(self, nums):
        begin, res = 0, []
        strout = lambda b, e: str(b) + "->" + str(e) if b != e else str(b)
        for i in range(1, len(nums)+1):
            if i == len(nums) or nums[i] - nums[i-1] != 1:
                res.append(strout(nums[begin], nums[i-1]))
                begin = i
        return res

Log in to reply

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