Ad platform~45 min2s · 256 MBtarget O(n log n) time, O(n) spacesegment-tree
An ad page is a canvas, and every banner is a rectangle placed on it. Banners can overlap, and a banner can sit inside another. A unit square of the canvas counts once, however many banners cover it.
Your team lead asks: "How much of the canvas is covered by at least one banner?" A page can have 30,000 banners, so overlapping areas must be counted once and the count must be fast.
Write union_area(banners).
banners[i] = [x1, y1, x2, y2] is a rectangle with its lower left corner at (x1, y1) and its upper right corner at (x2, y2). Always x1 < x2 and y1 < y2.Input: banners = [[1, 1, 4, 3], [2, 2, 6, 5]]
Output: 16The banners have areas 6 and 12, and they overlap in the rectangle from (2, 2) to (4, 3), which has area 2. Sweep a vertical line from left to right. At each event the covered height is the total length of y values with at least one banner:
| Event at x | Strip width since the last event | Covered height before | Area added | Event |
|---|---|---|---|---|
| 1 | 0 | 0 | 0 | the first banner opens, covering y from 1 to 3 |
| 2 | 1 | 2 | 2 | the second banner opens, covering y from 1 to 5 together |
| 4 | 2 | 4 | 8 | the first banner closes, leaving y from 2 to 5 |
| 6 | 2 | 3 | 6 | the second banner closes |
The total is 2 + 8 + 6 = 16.
Input: banners = [[0, 0, 2, 2], [2, 0, 4, 2]]
Output: 8The banners touch along the line x = 2. Their areas add up: 4 + 4.
Input: banners = [[0, 0, 3, 3], [1, 1, 2, 2]]
Output: 9The small banner lies inside the large one, so it adds nothing.
1 ≤ len(banners) ≤ 30,0000 ≤ x1 < x2 ≤ 1,000,000 and 0 ≤ y1 < y2 ≤ 1,000,000The page is up to a million units on each side, so counting cells one by one is impossible. Even the compressed grid of distinct edge coordinates has up to 60,000 columns and 60,000 rows, and checking every banner for every cell is about 10^14 steps. The covered area must come from the edges alone.