163. Missing Ranges - cocoder39/coco39_LC GitHub Wiki

163. Missing Ranges

class Solution:
    def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[List[int]]:
        start = lower
        res = []
        for num in nums:
            if num > start:
                res.append([start, num-1])
            start = num + 1
        if start <= upper:
            res.append([start, upper])
        return res

first is always the begin of missing range.

  • 1 first increase by 1 if an input number is covered
  • 2 once an input number is greater than first, it means there is a missing range (or a missing single number)
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
        vector<string> res;
        int first = lower, second; //first->second is a gap
        for (auto num : nums) {
            if (num >= lower && num <= upper) { //handle follow up case where inputs exceeds bound
                if (num == first) {
                    first++;
                } else if (num > first) {
                    second = num - 1; //second >= first
                    if (first == second) {
                        res.push_back(to_string(first));
                    } else {//first < second
                        res.push_back(to_string(first) + "->" + to_string(second));
                    }
                    first = num + 1;
                }
            }
        }
        if (first == upper) {
            res.push_back(to_string(upper));
        } else if (first < upper) {
            res.push_back(to_string(first) + "->" + to_string(upper));
        }
        return res;
    }
⚠️ **GitHub.com Fallback** ⚠️