array and hashmap June 11, 2023

Summary ranges

Time O(n) Space O(n) Open original problem

We will iterate over the array and find the ranges. Then we will map the ranges to the required format.

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        ranges = []
        for n in nums:
            if not ranges or n > ranges[-1][-1] + 1:
                ranges += [],
            ranges[-1][1:] = n,
        return ['->'.join(map(str, r)) for r in ranges]

Time complexity: O(n)
Space complexity: O(n)