Summary Ranges
Difficulty: Easy · Pattern: Intervals · LeetCode #228
Given a sorted, unique integer array, return the smallest list of ranges that covers all the numbers exactly. Format each range as "a->b" if a != b, or "a" otherwise.
Examples
text
[0,1,2,4,5,7] → ["0->2","4->5","7"]
[0,2,3,4,6,8,9] → ["0","2->4","6","8->9"]Hints
- Walk the array, extending the current run while each value is the previous value + 1.
Approach
Use two pointers. i marks a run's start, and j advances while nums[j+1] == nums[j] + 1. Emit the range, then set i = j + 1. O(n).
Complexity
Time: O(n). Space: O(1) besides the output.
Python solution
def summaryRanges(nums):
res, i, n = [], 0, len(nums)
while i < n:
j = i
while j + 1 < n 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 resJavaScript solution
function summaryRanges(nums) {
const res = [];
for (let i = 0; i < nums.length; ) {
let j = i;
while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1) j++;
res.push(i === j ? String(nums[i]) : `${nums[i]}->${nums[j]}`);
i = j + 1;
}
return res;
}