I have written the following code snippet to find the range summaries, i.e., when given a sorted integer array without any duplicates, it returns the summaries as:
/* IP: [0,1,2,4,5,7]
* OP: ["0->2","4->5","7"]
*/
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if(nums.empty())
return res;
for(int i=0; i<nums.size(); i++) {
int lowerRange=nums[i];
while(((i+1)<nums.size()) && (nums[i+1]-nums[i]==1))
i++;
int higherRange=nums[i];
if(lowerRange!=higherRange) {
string str=to_string(lowerRange)+"->"+to_string(higherRange);
res.push_back(str);
} else
res.push_back(to_string(lowerRange));
}
return res;
}
};
I am wondering about the time complexity of the above code snippet. In my opinion, I am doing some "task" (execution of the inner while loop) for each element in the array (using the outer for loop). Due to this, in the worst case, the complexity should be O(n^2) in my opinion. On the other hand, I am doubtful because I do i++ in the inner while loop, due to which, I won't do the "task" on all the elements using the outer for loop. Due to this increment, I am visiting all the elements only once in my entire code. So, this should make the complexity O(n). Could someone please confirm if the complexity is O(n^2) or O(n)?
O(n^2)then?