Separate Squares I - Problem
Imagine you're an architect tasked with dividing a city block into two equal-area zones using a horizontal line. The city contains various square buildings, and your job is to find the perfect height for this dividing line.
You are given a 2D integer array squares where each squares[i] = [x_i, y_i, l_i] represents:
x_i, y_i: coordinates of the bottom-left corner of square il_i: side length of square i
Your goal is to find the minimum y-coordinate of a horizontal line such that the total area of squares above the line equals the total area of squares below the line.
Important: Squares may overlap, and overlapping areas should be counted multiple times (each square contributes its full area). Answers within 10^-5 of the actual answer will be accepted.
Input & Output
example_1.py โ Basic Case
$
Input:
squares = [[0,0,2], [2,0,2]]
โบ
Output:
2.0
๐ก Note:
Two non-overlapping squares of area 4 each. Total area = 8, so we need 4 above and 4 below. The line at y=2 puts the first square entirely below (area 4) and the second square entirely above (area 4).
example_2.py โ Overlapping Squares
$
Input:
squares = [[0,0,4], [1,1,2]]
โบ
Output:
2.0
๐ก Note:
First square has area 16, second has area 4. Total area = 20, target = 10. At y=2: first square contributes 4*2=8 below, second contributes 2*1=2 below (total 10 below, 10 above).
example_3.py โ Single Square
$
Input:
squares = [[0,0,4]]
โบ
Output:
2.0
๐ก Note:
Single square from (0,0) to (4,4) with area 16. To split equally, we need area 8 above and 8 below. Line at y=2 divides the square perfectly in half.
Constraints
- 1 โค squares.length โค 105
- squares[i].length == 3
- 0 โค xi, yi โค 109
- 1 โค li โค 109
- Overlapping areas are counted multiple times
- Answer within 10-5 of actual answer will be accepted
Visualization
Tap to expand
Understanding the Visualization
1
Identify Critical Points
Mark all square boundaries as potential dividing lines
2
Binary Search Range
Use binary search between minimum and maximum y-coordinates
3
Calculate Areas
For each test line, compute total area above and below
4
Find Balance
Converge on the y-coordinate where areas are equal
Key Takeaway
๐ฏ Key Insight: Binary search on y-coordinates combined with efficient area calculation gives us O(n log(max_y)) solution, much faster than checking every possible boundary.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code