Iterate through sorted array tracking start of current range. Expand range while nums[i] + 1 == nums[i+1], then format output string.
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
res = []
i = 0
while i < len(nums):
start = nums[i]
while i + 1 < len(nums) and nums[i + 1] == nums[i] + 1:
i += 1
if start != nums[i]:
res.append(f"{start}->{nums[i]}")
else:
res.append(str(start))
i += 1
return res
class Solution {
public List summaryRanges(int[] nums) {
List res = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int start = nums[i];
while (i + 1 < nums.length && nums[i + 1] == nums[i] + 1) {
i++;
}
if (start != nums[i]) {
res.add(start + "->" + nums[i]);
} else {
res.add(String.valueOf(start));
}
}
return res;
}
}