163 Missing Ranges

Given a sorted integer array where the range of elements are in the inclusive range [lower,upper], return its missing ranges.

For example, given[0, 1, 3, 50, 75],lower= 0 and upper= 99, return["2", "4->49", "51->74", "76->99"].

vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) 
{
    vector<string> range_gaps;
    int low, high;

    // beginning range
    if (nums[0] - 1 == lower)
        range_gaps.push_back(to_string(lower));
    else if (lower < *nums.begin() - 2)
        range_gaps.push_back(to_string(lower) + "->" + to_string(nums[0] - 1));

    // inclusive range
    for (int i = 0; i < nums.size() - 1 && nums.at(i) >= lower && nums.at(i) <= upper; i++) {
        low = i;
        high = i + 1;

        if (nums[low] + 1 == nums[high]) continue;
        else if (nums[low] + 1 == nums[high] - 1) 
            range_gaps.push_back(to_string(nums[low] + 1));
        else 
            range_gaps.push_back(to_string(nums[low] + 1) + "->" + to_string(nums[high] - 1));
    }

    // ending range
    if (upper > *nums.rbegin() + 2) 
        range_gaps.push_back(to_string(*nums.rbegin() + 1) + "->" + to_string(upper));
    else if (*nums.rbegin() + 1 == upper - 1)
        range_gaps.push_back(to_string(*nums.rbegin() + 1));

    return range_gaps;
}

int main()
{
    vector<int> test = { 0,1,3,50,75 };
    vector<string> elements = findMissingRanges(test, 0, 99);
    print(elements);
}

Last updated