SDE & MLE Prep

228. Summary Ranges

Problem

Given a sorted array of distinct integers, cover it exactly with the fewest ranges of consecutive numbers and return them as strings: "a->b" for a range with more than one value, "a" for a single value.

Example: [0,1,2,4,5,7] → ["0->2","4->5","7"]

Extend a run while the next number is consecutive; emit "a->b" or "a".

Complexity: O(n).

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