#3454
Separate Squares II
HardArrayBinary SearchSegment TreeSweep LineSweep LineSegment Tree
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
This approach uses a sweep line technique combined with a segment tree to efficiently calculate the area covered by squares. It allows us to find the minimum y-coordinate where the areas above and below are equal without checking every possible line.
⚙️
Algorithm
3 steps- 1Step 1: Create events for the start and end of each square and sort them by y-coordinate.
- 2Step 2: Use a segment tree to maintain the active areas as we sweep through the y-coordinates.
- 3Step 3: Find the y-coordinate where the area above equals the area below using the segment tree.
solution.py16 lines
1def optimal(squares):
2 events = []
3 for x, y, l in squares:
4 events.append((y, l, 1))
5 events.append((y + l, l, -1))
6 events.sort()
7 total_area = sum(l * l for _, l, _ in squares)
8 active_area = 0
9 for y, l, typ in events:
10 if typ == 1:
11 active_area += l * l
12 else:
13 active_area -= l * l
14 if active_area * 2 == total_area:
15 return y
16 return -1ℹ
Complexity note: The complexity is dominated by the sorting of events, which is O(n log n), while maintaining the active area is linear.
- 1Overlapping areas should be counted only once.
- 2The line must lie within one of the squares.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.