Compress a Sorted List Into Ranges

easy array intervals

Problem

Given a sorted array of distinct integers, return the smallest list of ranges covering every value. A range like "2-5" stands for any maximal run of consecutive numbers; a singleton like "7" stands for one value with no neighbour. Walk the array remembering the start of the current run; emit a range each time the run breaks.

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