Leetcode 1893. Check if All the Integers in a Range Are Covered
You are given a 2D integer array ranges
and two integers left
and right
. Each ranges[i] = [starti, endi]
represents an inclusive interval [starti, endi]
.
Return true
if each integer in the inclusive interval [left, right]
is covered by at least one interval in ranges
. Otherwise, return false
.
ranges
always positive integers?left
and right
guaranteed to be within the range defined by elements in ranges
?However, we’ll assume general cases based on the prompt:
ranges
can have any integer ranges, including negative.[left, right]
may not be covered by any interval in ranges
.[left, right]
range.ranges
.ranges
.covered
array as true
.[left, right]
range are covered.true
if all are covered; otherwise, return false
.#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
vector<bool> covered(right - left + 1, false);
for (const auto& range : ranges) {
int start = max(left, range[0]);
int end = min(right, range[1]);
for (int i = start; i <= end; ++i) {
covered[i - left] = true;
}
}
for (bool isCovered : covered) {
if (!isCovered) return false;
}
return true;
}
};
covered
array: O(right - left + 1)covered
array per range: O(m * n) where m
is the number of ranges and n
is the largest size of the ranges (bounded by right - left + 1
).covered
array: O(right - left + 1)Thus, the total time complexity is O(m * (right - left + 1)).
This ensures effective handling of checking whether all integers within [left, right]
are covered by any of the intervals in ranges
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?