Approach
Sorting and greedy selection
For Check if Grid can be Cut into Sections, 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
- 37 lines of C++ from the credited upstream file 3394.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.
1class Solution {2 public:3 bool checkValidCuts(int n, vector<vector<int>>& rectangles) {4 vector<pair<int, int>> xs;5 vector<pair<int, int>> ys;6 7 for (const vector<int> rectangles : rectangles) {8 const int startX = rectangles[0];9 const int startY = rectangles[1];10 const int endX = rectangles[2];11 const int endY = rectangles[3];12 xs.emplace_back(startX, endX);13 ys.emplace_back(startY, endY);14 }15 16 return max(countMerged(xs), countMerged(ys)) >= 3;17 }18 19 private:20 int countMerged(vector<pair<int, int>>& intervals) {21 int count = 0;22 int prevEnd = 0;23 24 ranges::sort(intervals);25 26 for (const auto& [start, eend] : intervals)27 if (start < prevEnd) {28 prevEnd = max(prevEnd, eend);29 } else {30 prevEnd = eend;31 ++count;32 }33 34 return count;35 }36};37