228. Summary Ranges
Problem
Given a sorted array of distinct integers, cover it exactly with the fewest ranges of consecutive numbers and return them as strings: "a->b" for a range with more than one value, "a" for a single value.
Example: [0,1,2,4,5,7] → ["0->2","4->5","7"]
Extend a run while the next number is consecutive; emit "a->b" or "a".
Complexity: O(n).
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
res, i = [], 0
while i < len(nums):
j = i
while j + 1 < len(nums) 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 res
assert Solution().summaryRanges([0, 1, 2, 4, 5, 7]) == ["0->2", "4->5", "7"]
assert Solution().summaryRanges([]) == []
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
for (int i = 0, j; i < nums.length; i = j + 1) {
j = i;
while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) j++;
res.add(i == j ? String.valueOf(nums[i]) : nums[i] + "->" + nums[j]);
}
return res;
}
}
func summaryRanges(nums []int) []string {
res := []string{}
for i := 0; i < len(nums); {
j := i
for j+1 < len(nums) && nums[j+1] == nums[j]+1 {
j++
}
if i == j {
res = append(res, strconv.Itoa(nums[i]))
} else {
res = append(res, fmt.Sprintf("%d->%d", nums[i], nums[j]))
}
i = j + 1
}
return res
}