Separate Squares I - Problem

You are given a 2D integer array squares. Each squares[i] = [xi, yi, li] 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 of the squares above the line equals the total area of the squares below the line.

Note: Squares may overlap. Overlapping areas should be counted multiple times. Answers within 10^-5 of the actual answer will be accepted.

Input & Output

Example 1 — Basic Case
$ Input: squares = [[1,1,3],[1,4,3],[3,1,1]]
Output: 2.5
💡 Note: Square 1: bottom-left (1,1), area 9. Square 2: bottom-left (1,4), area 9. Square 3: bottom-left (3,1), area 1. At y=2.5: above line = 9+9+1=19, below line = 0. This is just an example - actual calculation considers partial intersections.
Example 2 — Single Square
$ Input: squares = [[0,0,4]]
Output: 2.0
💡 Note: One square from (0,0) to (4,4) with area 16. The horizontal line at y=2 divides it exactly in half: 8 area above, 8 area below.
Example 3 — Non-overlapping
$ Input: squares = [[0,0,2],[4,0,2]]
Output: 1.0
💡 Note: Two separate squares, each with area 4. Line at y=1 divides each square in half, giving 4 area above and 4 area below.

Constraints

  • 1 ≤ squares.length ≤ 105
  • squares[i].length == 3
  • 1 ≤ xi, yi, li ≤ 109

Visualization

Tap to expand
Separate Squares I INPUT S1 S2 S3 0 1 3 4 1 4 7 squares = [ [1,1,3], // S1: 3x3 [1,4,3], // S2: 3x3 [3,1,1] // S3: 1x1 ] Total Area = 9+9+1 = 19 ALGORITHM STEPS 1 Calculate Total Area Sum all squares: 9+9+1=19 2 Binary Search on Y Search range: [1, 7] 3 Compute Area Below For each y, calc below area 4 Find y: below = 9.5 Target: 19/2 = 9.5 Binary Search Progress y=4.0: below=10.0 (too high) y=2.5: below=9.5 (target!) y=3.25: below=11.25 At y=2.5: S1: 3*(2.5-1)=4.5 S2: 0 (above line) S3: 1*(2.5-1)=1.5 (capped) FINAL RESULT y=2.5 ABOVE BELOW Output: 2.5 Verification: Below: 4.5+0+5=9.5 Above: 4.5+9+0=9.5 OK Key Insight: Binary search finds the optimal y-coordinate where the cumulative area below equals half the total. For each candidate y, calculate partial areas of squares intersecting that horizontal line. Time Complexity: O(n log(max_y / epsilon)) | Space: O(1) TutorialsPoint - Separate Squares I | Optimal Solution (Binary Search)
Asked in
Google 25 Amazon 18 Microsoft 12
23.4K Views
Medium Frequency
~35 min Avg. Time
890 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