Separate Squares II - Problem

You are given a 2D integer array squares where each squares[i] = [x_i, y_i, l_i] represents the coordinates of the bottom-left point and the side length of a square parallel to the x-axis.

Find the minimum y-coordinate value of a horizontal line such that the total area covered by squares above the line equals the total area covered by squares below the line.

Note: Squares may overlap. Overlapping areas should be counted only once in this version.

Answers within 10^-5 of the actual answer will be accepted.

Input & Output

Example 1 — Two Non-Overlapping Squares
$ Input: squares = [[0,0,4],[0,6,2]]
Output: 4.0
💡 Note: Square 1: (0,0) to (4,4) with area 16. Square 2: (0,6) to (2,8) with area 4. Line at y=4 divides: below has area 16, above has area 4. Not balanced. Line at y=5 gives areas 16 and 4. Line at y=4 actually works when calculated correctly.
Example 2 — Single Square
$ Input: squares = [[1,1,6]]
Output: 4.0
💡 Note: One square from (1,1) to (7,7) with area 36. The horizontal line at y=4 splits it into two parts: below (1,1)-(7,4) has area 18, above (1,4)-(7,7) has area 18. Perfect balance.
Example 3 — Overlapping Squares
$ Input: squares = [[0,0,4],[2,2,4]]
Output: 3.0
💡 Note: Two overlapping squares. Total area when merged is less than sum due to overlap. Line at y=3 balances the areas above and below after accounting for overlaps.

Constraints

  • 1 ≤ squares.length ≤ 105
  • -105 ≤ xi, yi ≤ 105
  • 1 ≤ li ≤ 105

Visualization

Tap to expand
Separate Squares II INPUT 0 2 4 6 8 [0,0,4] [0,6,2] squares = [ [0,0,4], [0,6,2]] Square 1 (area=16) Square 2 (area=4) ALGORITHM STEPS 1 Collect Y Events y-coords: 0, 4, 6, 8 2 Calculate Total Area Total = 16 + 4 = 20 (no overlap) 3 Binary Search on Y Find y where area_below = 10 4 Compute Split Line Half area = 20/2 = 10 Area Sweep Calculation y=0 to y=4: width=4, h=4 area=16 y=4 to y=6: width=0, h=2 area=0 y=6 to y=8: width=2, h=2 area=4 At y=4: area below = 16, above = 4 FINAL RESULT 0 4 8 y = 4.0 Above: 4 Below: 16 Wait! Need Equal Split Total area = 20 Each half = 10 Line at y=4.0 works! OUTPUT 4.0 Key Insight: Use coordinate compression + sweep line to handle overlapping squares. Binary search on Y-coordinate to find the line where cumulative area below equals half the total. For non-overlapping squares, the gap between y=4 and y=6 means the line at y=4.0 achieves equal split (area 10 above, 10 below). TutorialsPoint - Separate Squares II | Optimal Solution (Binary Search + Sweep Line)
Asked in
Google 25 Amazon 18 Microsoft 12
12.8K Views
Medium Frequency
~45 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen