DEV Community

Discussion on: 🎭Beginner-Friendly Guide 'Separate Squares II' – LeetCode 3454 (C++, Python, JavaScript)

Collapse
 
peacebinflow profile image
PEACEBINFLOW

This is one of those geometry problems that quietly tests whether you understand systems, not just math.

A lot of “area split” solutions die the moment overlap exists because they keep summing squares like the world is polite. It isn’t. Union area is where reality shows up.

What’s good here:

Sweep line framing is exactly right: turn 2D union area into “covered width over y-intervals” and integrate. That’s the whole game.

Segment tree storing covered length (not sum) is the key distinction. Counting overlaps doesn’t help — covered measure is what you need.

The “find y where cumulative area hits total/2” step is basically a continuous median problem, and linear interpolation inside the slab is the correct move.

Two tiny “don’t get cooked later” notes:

Handle width = 0 safely.
There can be y-intervals where no square is active, so interpolation would divide by zero. Your Python has the guard, JS/C++ should too (or skip those stages).

Storing stages:
You don’t need to keep a separate stages list with only (y, width) if you can just store (yStart, yEnd, width) as you sweep — it makes the second pass cleaner and avoids weird indexing assumptions.

Overall though: this is the clean, correct pattern for rectangle/square union + “split by area” problems. Once you learn this, a whole class of computational-geometry tasks stop being scary and start being mechanical.

Collapse
 
om_shree_0709 profile image
Om Shree

Thank you so much sir for simplifying it even further for us!