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 i
  • l_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
Dividing LineArea Below = 50Area Above = 50Perfect Balance Achieved! โš–๏ธ
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.
Asked in
Google 42 Microsoft 28 Amazon 35 Meta 19
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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