#3453
Separate Squares I
MediumArrayBinary SearchBinary SearchArea Calculation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(maxY)) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n log(maxY))Space O(1)
We can use binary search to find the minimum y-coordinate efficiently by leveraging the cumulative area above and below a line. This reduces the number of checks needed.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total area of all squares.
- 2Step 2: Use binary search on the range of y-coordinates to find the line where the area above equals the area below.
- 3Step 3: For each mid-point in the binary search, calculate the areas above and below that line.
solution.py19 lines
1# Full working Python code
2def min_y_coordinate(squares):
3 total_area = sum(l * l for _, _, l in squares)
4 low, high = 0, 10**9
5
6 while low < high:
7 mid = (low + high) / 2
8 area_above = 0
9 area_below = 0
10 for x, y, l in squares:
11 if y + l > mid:
12 area_above += (min(y + l, mid) - mid) * l
13 if y < mid:
14 area_below += (min(mid, y + l) - y) * l
15 if area_above < area_below:
16 low = mid + 1
17 else:
18 high = mid
19 return lowℹ
Complexity note: The time complexity is O(n log(maxY)) because we perform a binary search over the range of possible y-coordinates, checking the area for each square in O(n) time.
- 1Understanding how areas above and below a line can be calculated is crucial.
- 2Binary search can significantly reduce the number of checks needed to find the correct y-coordinate.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.