Approach
Sorting and greedy selection
For Rectangle Area II, 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
- 61 lines of C++ from the credited upstream file 850.cpp.
- The implementation visibly relies on sequence storage.
- 3 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.
1struct Event {2 int x;3 int y1;4 int y2;5 char type;6};7 8class Solution {9 public:10 int rectangleArea(vector<vector<int>>& rectangles) {11 constexpr int kMod = 1'000'000'007;12 vector<Event> events;13 14 for (const vector<int>& r : rectangles) {15 events.emplace_back(r[0], r[1], r[3], 's');16 events.emplace_back(r[2], r[1], r[3], 'e');17 }18 19 ranges::sort(events, ranges::less{},20 [](const Event& event) { return event.x; });21 22 long ans = 0;23 int prevX = 0;24 vector<pair<int, int>> yPairs;25 26 for (const auto& [currX, y1, y2, type] : events) {27 if (currX > prevX) {28 const int width = currX - prevX;29 ans = (ans + width * getHeight(yPairs)) % kMod;30 prevX = currX;31 }32 if (type == 's') {33 yPairs.emplace_back(y1, y2);34 ranges::sort(yPairs);35 } else { 36 const auto it =37 find(yPairs.begin(), yPairs.end(), pair<int, int>(y1, y2));38 yPairs.erase(it);39 }40 }41 42 return ans % kMod;43 }44 45 private:46 long getHeight(const vector<pair<int, int>>& yPairs) {47 int height = 0;48 int prevY = 0;49 50 for (const auto& [y1, y2] : yPairs) {51 prevY = max(prevY, y1);52 if (y2 > prevY) {53 height += y2 - prevY;54 prevY = y2;55 }56 }57 58 return height;59 }60};61