- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 40 lines of C++ from the credited upstream file 699.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 vector<int> fallingSquares(vector<vector<int>>& positions) {4 vector<int> ans;5 map<pair<int, int>, int> xsToHeight; 6 int maxHeight = INT_MIN;7 8 for (const vector<int>& p : positions) {9 const int left = p[0];10 const int sideLength = p[1];11 const int right = left + sideLength;12 13 auto it = xsToHeight.upper_bound({left, right});14 if (it != xsToHeight.begin() && (--it)->first.second <= left)15 ++it;16 int maxHeightInRange = 0;17 vector<tuple<int, int, int>> ranges;18 while (it != xsToHeight.end() && it->first.first < right) {19 const int l = it->first.first;20 const int r = it->first.second;21 const int h = it->second;22 if (l < left)23 ranges.emplace_back(l, left, h);24 if (right < r)25 ranges.emplace_back(right, r, h);26 maxHeightInRange = max(maxHeightInRange, h);27 it = xsToHeight.erase(it);28 }29 const int newHeight = maxHeightInRange + sideLength;30 xsToHeight[{left, right}] = newHeight;31 for (const auto& [l, r, h] : ranges)32 xsToHeight[{l, r}] = h;33 maxHeight = max(maxHeight, newHeight);34 ans.push_back(maxHeight);35 }36 37 return ans;38 }39};40