You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.
Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.
Return the total area. Since the answer may be too large, return it modulo109 + 7.
Input: rectangles =[[0,0,2,2],[1,0,2,3],[1,0,3,1]]Output: 6Explanation: A total area of 6is covered by all three rectangales, as illustrated in the picture.From(1,1) to (2,2), the green and red rectangles overlap.From(1,0) to (2,3), all three rectangles overlap.
Example 2:
1
2
3
Input: rectangles =[[0,0,1000000000,1000000000]]Output: 49Explanation: The answer is1018modulo(10^9+7), which is49.
To find the total area covered by rectangles (with overlaps counted only once), we can use a line sweep algorithm. We process all vertical edges (events) of rectangles, keep track of active intervals on the y-axis, and sum up the area covered as we sweep from left to right.
For each rectangle, create two events: one for the left edge (add interval) and one for the right edge (remove interval).
Sort all events by x-coordinate.
Use a segment tree or a list to maintain active y-intervals.
As we sweep from left to right, for each x, calculate the total y-length covered by active intervals and multiply by the width (difference in x) to get the area for that segment.
Add up all such areas and return the result modulo 1e9+7.
classSolution {
funrectangleArea(R: Array<IntArray>): Int {
val mod = 1_000_000_7
val Y = mutableListOf<Int>()
for (r in R) { Y.add(r[1]); Y.add(r[3]) }
val yList = Y.distinct().sorted()
val events = mutableListOf<IntArray>()
for (r in R) {
events.add(intArrayOf(r[0], r[1], r[3], 1))
events.add(intArrayOf(r[2], r[1], r[3], -1))
}
events.sortBy { it[0] }
val count = IntArray(yList.size)
var prevX = 0var curY = 0var res = 0for (e in events) {
val(x, y1, y2, sig) = e
res = ((res + 1L * curY * (x - prevX)) % mod).toInt()
prevX = x
for (j in yList.indices) {
if (yList[j] >= y1 && yList[j] < y2) count[j] += sig
}
curY = 0for (j in0 until yList.size-1) {
if (count[j] > 0) curY += yList[j+1] - yList[j]
}
}
return res
}
}
classSolution:
defrectangleArea(self, R: list[list[int]]) -> int:
MOD =10**9+7 Y = sorted(set([y for x1, y1, x2, y2 in R for y in (y1, y2)]))
events = []
for x1, y1, x2, y2 in R:
events.append((x1, y1, y2, 1))
events.append((x2, y1, y2, -1))
events.sort()
count = [0]*len(Y)
prev_x =0 cur_y_sum =0 res =0for x, y1, y2, sig in events:
res = (res + cur_y_sum * (x - prev_x)) % MOD
prev_x = x
for j in range(len(Y)):
if Y[j] >= y1 and Y[j] < y2:
count[j] += sig
cur_y_sum =0for j in range(len(Y)-1):
if count[j] >0:
cur_y_sum += Y[j+1] - Y[j]
return res