[LeetCode] Find Maximal Uncovered Ranges

2655. Find Maximal Uncovered Ranges

You are given an integer n which is the length of a 0-indexed array nums, and a 0-indexed 2D-array ranges, which is a list of sub-ranges of nums (sub-ranges may overlap).

Each row ranges[i] has exactly 2 cells:

  • ranges[i][0], which shows the start of the ith range (inclusive)
  • ranges[i][1], which shows the end of the ith range (inclusive)

These ranges cover some cells of nums and leave some cells uncovered. Your task is to find all of the uncovered ranges with maximal length.

Return a 2D-array answer of the uncovered ranges, sorted by the starting point in ascending order.

By all of the uncovered ranges with maximal length, we mean satisfying two conditions:

  • Each uncovered cell should belong to exactly one sub-range
  • There should not exist two ranges (l1, r1) and (l2, r2) such that r1 + 1 = l2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
map<int, int> range;
void add(int s, int e) {
if(!range.count(s)) range[s] = -1;
range[s] = max(range[s], e);
auto it = range.lower_bound(s);
if(it != begin(range) and prev(it)->second + 1 >= s) {
prev(it)->second = max(prev(it)->second, e);
it = prev(it);
}
while(next(it) != end(range) and it->second + 1 >= next(it)->first) {
it->second = max(it->second, next(it)->second);
range.erase(next(it));
}
}
public:
vector<vector<int>> findMaximalUncoveredRanges(int n, vector<vector<int>>& ranges) {
range.clear();
add(-1,-1);
add(n,n);
for(auto r : ranges) {
add(r[0],r[1]);
}
vector<vector<int>> res;
for(auto it = begin(range); next(it) != end(range); it++) {
int l = it->second + 1, r = next(it)->first - 1;
if(0 <= l and l <= n and 0 <= r and r <= n) res.push_back({l,r});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/01/PS/LeetCode/find-maximal-uncovered-ranges/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.