https://leetcode.com/problems/summary-ranges/description/

C++

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ranges;

        for(int i = 0; i < nums.size(); i++){
            int start = nums[i];
            // Keep iterating until the next elemet is the one more than the current element
            while(i + 1 < nums.size() && nums[i] + 1 == nums[i + 1]){
                i++;
            }

            if (start != nums[i]){
                ranges.push_back(to_string(start) + "->" + to_string(nums[i]));
            }
            else{
                ranges.push_back(to_string(start));
            }
        }
        return ranges;
    }
};

Complexity Analysis

Here $n$ is the number of elements in nums.

Python

def summaryRanges(self, nums: List[int]) -> List[str]:
    intervals = []
    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]:
            intervals.append(f"{start}->{nums[i]}")
        else:
            intervals.append(f"{start}")
        
        i += 1
    return intervals

$Time=O(N)$

$Space=O(1)$