Summary Ranges

easy array intervals

Problem

You are given a sorted unique integer array nums. Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Inputnums = [0,1,2,4,5,7]
Output["0->2","4->5","7"]
Three runs: 0..2, 4..5, and a lone 7.

def summary_ranges(nums):
    out = []
    i = 0
    while i < len(nums):
        j = i
        while j + 1 < len(nums) and nums[j + 1] == nums[j] + 1:
            j += 1
        out.append(str(nums[i]) if i == j else f"{nums[i]}->{nums[j]}")
        i = j + 1
    return out
function summaryRanges(nums) {
  const out = [];
  let i = 0;
  while (i < nums.length) {
    let j = i;
    while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1) j++;
    out.push(i === j ? String(nums[i]) : nums[i] + "->" + nums[j]);
    i = j + 1;
  }
  return out;
}
class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> out = new ArrayList<>();
        int i = 0;
        while (i < nums.length) {
            int j = i;
            while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) j++;
            out.add(i == j ? String.valueOf(nums[i]) : nums[i] + "->" + nums[j]);
            i = j + 1;
        }
        return out;
    }
}
vector<string> summaryRanges(vector<int>& nums) {
    vector<string> out;
    int i = 0;
    while (i < (int)nums.size()) {
        int j = i;
        while (j + 1 < (int)nums.size() && nums[j + 1] == nums[j] + 1) ++j;
        if (i == j) out.push_back(to_string(nums[i]));
        else out.push_back(to_string(nums[i]) + "->" + to_string(nums[j]));
        i = j + 1;
    }
    return out;
}
Time: O(n) Space: O(1) extra