[LeetCode] Filter Occupied Intervals

3975. Filter Occupied Intervals

You are given a 2D integer array occupiedIntervals, where occupiedIntervals[i] = [start_i, end_i] represents a time interval during which you are occupied. Each interval starts at start_i and ends at end_i, inclusive. These intervals may overlap.

You are also given two integers freeStart and freeEnd, which define a free time interval from freeStart to freeEnd, inclusive.

Your task is to merge all occupied intervals that overlap or touch, then remove all integer points in the free interval from the merged occupied intervals.

Two intervals touch if the second interval starts immediately after the first one ends. For example, [1, 1] and [2, 2] touch and should be merged into [1, 2].

Return the remaining occupied intervals in sorted order. The returned intervals must be non-overlapping and must contain the minimum number of intervals possible. If there are no remaining occupied points, return an empty list.

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
32
class Solution {
vector<vector<int>> merge(vector<vector<int>>& A) {
vector<vector<int>> res;
sort(begin(A), end(A));
for(auto& a : A) {
if(res.size() and res.back().back() + 1 >= a[0]) {
res.back().back() = max(res.back().back(), a[1]);
} else res.push_back(a);
}
return res;
}
public:
vector<vector<int>> filterOccupiedIntervals(vector<vector<int>>& occupiedIntervals, int freeStart, int freeEnd) {
vector<vector<int>> A = merge(occupiedIntervals);
vector<vector<int>> res;
for(auto& a : A) {
if(a[1] < freeStart or a[0] > freeEnd) res.push_back(a);
else {
int l = a[0], r = a[1];
if(freeStart <= l and l <= freeEnd) l = freeEnd + 1;
if(freeStart <= r and r <= freeEnd) r = freeStart - 1;
if(l > r) continue;
if(l > freeEnd or r < freeStart) res.push_back({l,r});
else {
res.push_back({l,freeStart - 1});
res.push_back({freeEnd+1, r});
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/filter-occupied-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.