Approach
Sorting and greedy selection
For Filter Occupied Intervals, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 43 lines of C++ from the credited upstream file filter-occupied-intervals.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<vector<int>> filterOccupiedIntervals(vector<vector<int>>& occupiedIntervals, int freeStart, int freeEnd) {8 const auto& merged_intervals = [](auto& occupiedIntervals) {9 ranges::sort(occupiedIntervals, [](const auto& a, const auto& b) {10 return a[0] < b[0];11 });12 vector<vector<int>> result;13 for (const auto& x : occupiedIntervals) {14 if (empty(result) || result.back()[1] + 1 < x[0]) {15 result.emplace_back(x);16 } else {17 result.back()[1] = max(result.back()[1], x[1]);18 }19 }20 return result;21 };22 23 const auto& overlapped = [](const auto& a, const auto& b) {24 return max(a[0], b[0]) <= min(a[1], b[1]);25 };26 27 vector<vector<int>> result;28 for (const auto& x : merged_intervals(occupiedIntervals)) {29 if (!overlapped(x, vector<int>{freeStart, freeEnd})) {30 result.emplace_back(x);31 continue;32 }33 if (x[0] <= freeStart - 1) {34 result.push_back({x[0], freeStart - 1});35 }36 if (freeEnd + 1 <= x[1]) {37 result.push_back({freeEnd + 1, x[1]});38 }39 }40 return result;41 }42};43