EasyNo. 0228
Summary Ranges — LeetCode 228 Python Solution
- Topics
- Array
- On a study list
- Top Interview 150
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
| 0717 | 1-bit and 2-bit Characters | Easy |
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.