C++ w/ 0ms. O(n) and O(1) space.


  • 0
    H
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            int len = nums.size();
            vector<string> ranges;
            if(!len){
                return ranges;
            }
            int start = 0 , end = 0;
            
            while(end+1 < len){
                if(nums[end]+1 != nums[end+1]){
                    if(start == end){
                        ranges.push_back(to_string(nums[start]));
                    }else{
                        ranges.push_back(to_string(nums[start])+"->"+to_string(nums[end]));
                    }
                    start = end+1;
                }
                end++;
            }
            if(start == end){
                ranges.push_back(to_string(nums[start]));
            }else{
                ranges.push_back(to_string(nums[start])+"->"+to_string(nums[end]));
            }
            return ranges;
        }
    };
    

    To solve this there are two pointers 'start' and 'end' which keeps track of where the range lies.
    Keep iterating the end pointer and check if the next value lies within range . if not , update start and end pointers and push back to the list.
    If start == end it means we have just one element in that range otherwise more than one.
    Last code it because we are left with last range of elements.
    Please comment for further improvement.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.