Problem solution · C++

Separate Squares II

Separate Squares II: a C++ solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Segment tree or range structure
Source
walkccc LeetCode Solutions
Length
94 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Segment tree or range structure

For Separate Squares II, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 94 lines of C++ from the credited upstream file 3454.cpp.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • 3 loop blocks detected.

Complexity

Count the build once, then multiply the logarithmic update or query path by the number of operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSeparate Squares II · C++C++
Use this to learn the idea, then write your own version.
class SegmentTree { public:  explicit SegmentTree(const vector<int>& xs)      : xs(xs), n(xs.size() - 1), coveredCount(4 * n), coveredWidth(4 * n) {}   // Adds val to the range [i, j].  void add(int i, int j, int val) {    add(0, 0, n - 1, i, j, val);  }   // Returns the covered width of xs[0..n - 1].  int getCoveredWidth() const {    return coveredWidth[0];  }  private:  const int n;  // the number of segments (|xs| - 1)  vector<int> xs;  vector<int> coveredCount;  vector<int> coveredWidth;   void add(int treeIndex, int lo, int hi, int i, int j, int val) {    if (j <= xs[lo] || xs[hi + 1] <= i)      return;    if (i <= xs[lo] && xs[hi + 1] <= j) {      coveredCount[treeIndex] += val;    } else {      const int mid = (lo + hi) / 2;      add(2 * treeIndex + 1, lo, mid, i, j, val);      add(2 * treeIndex + 2, mid + 1, hi, i, j, val);    }    if (coveredCount[treeIndex] > 0) {      coveredWidth[treeIndex] = xs[hi + 1] - xs[lo];    } else if (lo == hi) {      coveredWidth[treeIndex] = 0;    } else {      coveredWidth[treeIndex] =          coveredWidth[2 * treeIndex + 1] + coveredWidth[2 * treeIndex + 2];    }  }}; class Solution { public:  double separateSquares(vector<vector<int>>& squares) {    vector<tuple<int, int, int, int>> events;  // (y, delta, xl, xr)    set<int> xs;     for (const vector<int>& square : squares) {      const int x = square[0];      const int y = square[1];      const int l = square[2];      events.emplace_back(y, 1, x, x + l);      events.emplace_back(y + l, -1, x, x + l);      xs.insert(x);      xs.insert(x + l);    }     ranges::sort(events);     const double halfArea = getArea(events, xs) / 2.0;    long area = 0;    int prevY = 0;    SegmentTree tree({xs.begin(), xs.end()});     for (const auto& [y, delta, xl, xr] : events) {      const int coveredWidth = tree.getCoveredWidth();      const long areaGain = coveredWidth * static_cast<long>(y - prevY);      if (area + areaGain >= halfArea)        return prevY + (halfArea - area) / coveredWidth;      area += areaGain;      tree.add(xl, xr, delta);      prevY = y;    }     throw;  }  private:  // Returns the total area of the rectangles.  long getArea(const vector<tuple<int, int, int, int>>& events,               const set<int>& xs) {    long totalArea = 0;    int prevY = 0;    SegmentTree tree({xs.begin(), xs.end()});    for (const auto& [y, delta, xl, xr] : events) {      totalArea += tree.getCoveredWidth() * static_cast<long>(y - prevY);      tree.add(xl, xr, delta);      prevY = y;    }    return totalArea;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗