Summary Ranges
LeetCode 228 · Easy · solution, intuition & step-by-step walkthrough
Extend consecutive runs.
This is how I solved Summary Ranges (LeetCode 228), an easy problem from the Intervals pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk the sorted list and extend a run while each next number is exactly one more. When the run breaks, write it as 'a->b' (or just 'a' for a single number).
Approach
- 1
start = nums[i].
- 2
Advance while nums[i+1] == nums[i] + 1.
- 3
Record start->end or start.
How I solved it
Run extensionPythonO(n) time
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
i=0
res=[]
n = len(nums)
while i<n:
start = nums[i]
while i+1<n and nums[i+1]==nums[i]+1:
i+=1
end = nums[i]
if start!=end:
res.append(f"{start}->{end}")
else:
res.append(f"{start}")
i+=1
return resSummary Ranges — FAQ
What is the intuition behind Summary Ranges?
Walk the sorted list and extend a run while each next number is exactly one more. When the run breaks, write it as 'a->b' (or just 'a' for a single number).
How do you solve Summary Ranges (LeetCode 228)?
1. start = nums[i]. 2. Advance while nums[i+1] == nums[i] + 1. 3. Record start->end or start.
What is the time and space complexity of Summary Ranges?
Time: O(n). Space: O(1) extra. (Accepted approach: Run extension.)
What are common mistakes in Summary Ranges?
Empty input returns [].