Skip to content

Commit db2fc0e

Browse files
authored
Create check-if-all-the-integers-in-a-range-are-covered.cpp
1 parent b77e1d8 commit db2fc0e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Time: O(n + r)
2+
// Space: O(r)
3+
4+
// if r is small, this is better
5+
class Solution {
6+
public:
7+
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
8+
static const int RANGE_SIZE = 50;
9+
10+
vector<int> interval(RANGE_SIZE + 1);
11+
for (const auto& r : ranges) {
12+
++interval[r[0] - 1];
13+
--interval[(r[1] - 1) + 1];
14+
}
15+
for (int i = 0, cnt = 0; i <= right - 1; ++i) {
16+
cnt += interval[i];
17+
if (i >= left - 1 && !cnt) {
18+
return false;
19+
}
20+
}
21+
return true;
22+
}
23+
};
24+
25+
// Time: O(nlogn)
26+
// Space: O(1)
27+
// if r is big, this is better
28+
class Solution2 {
29+
public:
30+
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
31+
sort(begin(ranges), end(ranges));
32+
for (const auto& r : ranges) {
33+
if (r[0] <= left && left <= r[1]) {
34+
left = r[1] + 1;
35+
}
36+
}
37+
return left > right;
38+
}
39+
};
40+
41+
// Time: O(n * r)
42+
// Space: O(1)
43+
class Solution3 {
44+
public:
45+
bool isCovered(vector<vector<int>>& ranges, int left, int right) {
46+
for (int i = left; i <= right; ++i) {
47+
bool found = false;
48+
for (const auto& r : ranges) {
49+
if (r[0] <= i && i <= r[1]) {
50+
found = true;
51+
break;
52+
}
53+
}
54+
if (!found) {
55+
return false;
56+
}
57+
}
58+
return true;
59+
}
60+
};

0 commit comments

Comments
 (0)