Find horizontal cut balancing square areas
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates computational geometry and algorithm design skills, focusing on area computation, monotonicity reasoning, existence proofs, root-finding under floating-point constraints, and considerations of numerical stability and complexity.
Part 1: Balanced Horizontal Cut in Non-Overlapping Squares
Constraints
- 1 <= len(squares) <= 200000
- Each square is [x, y, s] with x and y real-valued and s an integer
- 1 <= s <= 10^6
- Squares do not overlap in interior area
- 0 < eps <= 1e-3
Examples
Input: ([[0, 0, 2]],)
Expected Output: 1.0
Explanation: A 2x2 square has total area 4, so each side must contain area 2. The cut is halfway down the square at y = 1.0.
Input: ([[0, 0, 2], [3, 4, 2]],)
Expected Output: 2.0
Explanation: The first square contributes area 4 above y = 2, and the second square starts at y = 4. Any cut in [2, 4] balances the areas, so the smallest valid cut is 2.0.
Input: ([[0, 0, 1], [2, 0, 1], [0, 2, 2]],)
Expected Output: 2.5
Explanation: The two 1x1 squares contribute area 2 above y = 2. The total area is 6, so we need area 3 above the cut. That requires 1 more unit from the 2x2 square, which happens after going 0.5 units into it: y = 2.5.
Input: ([[5, -5, 5]],)
Expected Output: -2.5
Explanation: The square spans from y = -5 to y = 0. Its midpoint is y = -2.5, which splits its area equally.
Input: ([[0, 0, 2], [3, 0, 1]],)
Expected Output: 0.83333
Explanation: The total area is 5, so the target above-area is 2.5. From y = 0 to y = 1, the combined active width is 3, so the cut is at 2.5 / 3 = 0.83333 after rounding.
Hints
- Let F(y) be the total area of all squares above the cut. What shape does F(y) have as y moves downward?
- A valid search interval is from the smallest square top to the largest square bottom.
Part 2: Balanced Horizontal Cut in Overlapping Squares Using Union Area
Constraints
- 1 <= len(squares) <= 20000
- Each square is [x, y, s] with x and y real-valued and s an integer
- 1 <= s <= 10^6
- Squares may overlap arbitrarily
- Coordinates have absolute value at most 10^9
Hints
- Sweep along y. Between two consecutive top/bottom edges, the set of active squares does not change, so the covered x-length is constant.
- To get union width quickly for active x-intervals, coordinate compression plus a segment tree is a standard approach.
Part 3: Balanced Horizontal Cut in Non-Overlapping Rectangles
Constraints
- 1 <= len(rectangles) <= 200000
- Each rectangle is [x, y, w, h] with x and y real-valued
- w > 0 and h > 0
- Rectangles do not overlap in interior area
- Coordinates have absolute value at most 10^9
Hints
- Between consecutive rectangle top/bottom edges, the area gained per unit of y is constant.
- In each horizontal strip, that rate is the sum of widths of all rectangles crossing the strip.