# Missing Ranges in C++

Suppose we have a sorted integer array nums, the range of elements are in the inclusive range [lower, upper], we have to find the missing ranges.

So, if the input is like nums = [0, 1, 3, 50, 75], and lower value is 0 and upper value is 99, then the output will be ["2", "4->49", "51->74", "76->99"]

To solve this, we will follow these steps −

• Define an array nums

• Define one set v

• for initialize i := 0, when i < size of t, update (increase i by 1), do −

• if t[i] is not in v, then −

• insert t[i] into v

• insert t[i] at the end of nums

• define one array called ret

• curr := lower

• i := 0, n := size of nums

• while curr <= upper, do −

• if i < n and nums[i] is same as curr, then −

• (increase i by 1)

• (increase curr by 1)

• Otherwise

• temp := convert curr to string

• (increase curr by 1)

• if i < n and nums[i] is same as curr, then −

• insert temp at the end of ret

• Ignore following part, skip to the next iteration

• Otherwise

• if i is same as n, then −

• if curr <= upper, then −

• temp := "->"

• temp := temp concatenate upper as string

• curr := upper + 1

• insert temp at the end of ret

• Otherwise

• temp := "->"

• curr := nums[i]

• temp := temp concatenate (curr - 1) as string

• curr := nums[i]

• insert temp at the end of ret

• return ret

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<string< findMissingRanges(vector<int<& t, int lower, int upper) {
vector <int< nums;
set <long long int> v;
for(int i = 0; i < t.size(); i++){
if(!v.count(t[i])){
v.insert(t[i]);
nums.push_back(t[i]);
}
}
vector < string > ret;
long long int curr = lower;
int i = 0;
int n = nums.size();
while(curr <= upper){
if(i < n && nums[i] == curr){
i++;
curr++;
}
else{
string temp = to_string(curr);
curr++;
if(i < n && nums[i] == curr){
ret.push_back(temp);
continue;
}
else{
if(i == n){
if(curr <= upper){
temp += "->";
temp += to_string(upper);
curr = (long long int )upper + 1;
}
ret.push_back(temp);
}
else{
temp += "->";
curr = nums[i];
temp += to_string(curr - 1);
curr = nums[i];
ret.push_back(temp);
}
}
}
}
return ret;
}
};
main(){
Solution ob;
vector<int< v = {0,1,3,50,75};
print_vector(ob.findMissingRanges(v, 0, 99));
}

## Input

{0,1,3,50,75}, 0, 99

## Output

[2, 4->49, 51->74, 76->99, ]

Updated on: 18-Nov-2020

111 Views

##### Kickstart Your Career

Get certified by completing the course