Leetcode 163 Solution

This article provides solution to leetcode question 163 (missing-ranges)

https://leetcode.com/problems/missing-ranges

Solution

class Solution {
public:
    string get_range(int left, int right)
    {
        if (left == right)
            return to_string(left);
        else
            return to_string(left) + "->" + to_string(right);
    }

    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
        vector<string> res;

        if (nums.empty())
        {
            res.push_back(get_range(lower, upper));
            return res;
        }

        for (int i = 0; i < nums.size(); i++)
        {
            int left = 0;
            int right = nums[i] - 1;

            if (i == 0 && nums[i] != lower)
                left = lower;
            else if (i != 0 && (int64_t)nums[i] > (int64_t)nums[i - 1] + 1)
                left = nums[i - 1] + 1;
            else
                continue;

            res.push_back(get_range(left, right));
        }

        if (nums.back() != upper)
            res.push_back(get_range(nums.back() + 1, upper));

        return res;
    }
};