Siqi Liu / 1893-Check if all integers in the region are covered

Created Fri, 23 Jul 2021 00:00:00 +0000 Modified Thu, 25 Dec 2025 09:08:55 +0000
337 Words

I didn’t think of any good way to get it, so I used brute force to solve it first.

var isCovered = function(ranges, left, right) {
    for(let i = left ; i <= right ; i ++) {
        let include = false        for(let index = 0 ; index < ranges.length ; index ++) {
            let [start,end] = ranges[index]
            if (i >=start && i <=end) {
                include = true            }
        }
        if (!include) return false    }
    return true};

Thinking about optimization, you can use start, end. When start <= left, the [left … end] set is already included. Continue compressing [end + 1, right] until there are no elements in the set.

var isCovered = function(ranges, left, right) {
    ranges = ranges.sort((a,b) => a - b)
    for(let i = 0 ; i < ranges.length;i++) {
        let [start,end] = ranges[i];        // Shrink the left boundary according to the range if (start <= left) {
            left = Math.max(end,right)
        }
        if (left >= right) {
            return true        }
    }
    return left >= right
};

I didn’t think of any good way to get it, so I used brute force to solve it first.

var isCovered = function(ranges, left, right) {
    for(let i = left ; i <= right ; i ++) {
        let include = false        for(let index = 0 ; index < ranges.length ; index ++) {
            let [start,end] = ranges[index]
            if (i >=start && i <=end) {
                include = true            }
        }
        if (!include) return false    }
    return true};

Thinking about optimization, you can use start, end. When start <= left, the [left … end] set is already included. Continue compressing [end + 1, right] until there are no elements in the set.

var isCovered = function(ranges, left, right) {
    ranges = ranges.sort((a,b) => a - b)
    for(let i = 0 ; i < ranges.length;i++) {
        let [start,end] = ranges[i];        // Shrink the left boundary according to the range if (start <= left) {
            left = Math.max(end,right)
        }
        if (left >= right) {
            return true        }
    }
    return left >= right
};