Summary Ranges — LeetCode 228 Python Solution
EasyArray
- Problem
- #228
- Reading time
- 3 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.