#850
Rectangle Area II
HardArraySegment TreeSweep LineOrdered SetSweep 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)
The optimal solution uses a sweep line algorithm combined with a segment tree to efficiently calculate the area covered by rectangles, handling overlaps without explicitly checking each pair.
⚙️
Algorithm
3 steps- 1Step 1: Create events for the start and end of each rectangle.
- 2Step 2: Sort events by x-coordinate. For each event, update the segment tree to reflect the active rectangles.
- 3Step 3: Calculate the area covered by the active rectangles between consecutive x-coordinates.
solution.py35 lines
1# Full working Python code
2class Solution:
3 def computeArea(self, rectangles):
4 events = []
5 for x1, y1, x2, y2 in rectangles:
6 events.append((x1, y1, y2, 1)) # Start of rectangle
7 events.append((x2, y1, y2, -1)) # End of rectangle
8 events.sort()
9
10 def calculate_active_length(active_intervals):
11 length = 0
12 prev_y = -1
13 for y1, y2 in active_intervals:
14 if y1 > prev_y:
15 length += y2 - y1
16 prev_y = y2
17 elif y2 > prev_y:
18 length += y2 - prev_y
19 prev_y = y2
20 return length
21
22 active_intervals = []
23 total_area = 0
24 prev_x = events[0][0]
25
26 for x, y1, y2, typ in events:
27 total_area += calculate_active_length(active_intervals) * (x - prev_x)
28 if typ == 1:
29 active_intervals.append((y1, y2))
30 else:
31 active_intervals.remove((y1, y2))
32 active_intervals.sort()
33 prev_x = x
34
35 return total_area % (10**9 + 7)ℹ
Complexity note: The complexity is dominated by the sorting of events, which is O(n log n), and maintaining the active intervals using a map or segment tree.
- 1Understanding how to handle overlapping areas is crucial.
- 2Using data structures like segment trees can significantly optimize the area calculation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.