Summary Ranges — LeetCode 228 Python Solution

EasyArray
Problem
#228
Reading time
3 min

The problem

You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive).

Example

Input
nums = [0,1,2,4,5,7]
Output
["0->2","4->5","7"]
Explanation
The ranges are:

Python solution

Python
class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        def f(i: int, j: int) -> str:
            return str(nums[i]) if i == j else f'{nums[i]}->{nums[j]}'

        i = 0
        n = len(nums)
        ans = []
        while i < n:
            j = i
            while j + 1 < n and nums[j + 1] == nums[j] + 1:
                j += 1
            ans.append(f(i, j))
            i = j + 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 228. Summary Ranges?
LeetCode 228. Summary Ranges is rated Easy on LeetCode.
What topics does LeetCode 228. Summary Ranges cover?
LeetCode 228. Summary Ranges is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview