Rectangle Area
MediumGeometry · NVIDIA
Two rectangles on a plane have sides parallel to the axes. Rectangle A has bottom-left corner (ax1, ay1) and top-right corner (ax2, ay2); rectangle B has bottom-left corner (bx1, by1) and top-right corner (bx2, by2).
Return the total area covered by the two rectangles together. A region covered by both rectangles is counted only once. Rectangles that only touch along an edge or at a corner share no area.
Example 1
- Input:
- ax1 = 0, ay1 = 0, ax2 = 4, ay2 = 3, bx1 = 2, by1 = 1, bx2 = 6, by2 = 5
- Output:
- 24
- Explanation
- A has area 4 * 3 = 12 and B has area 4 * 4 = 16. They overlap where x is in [2, 4] and y is in [1, 3], a 2 by 2 square of area 4, so the union is 12 + 16 - 4 = 24.
Example 2
- Input:
- ax1 = -5, ay1 = -5, ax2 = 5, ay2 = 5, bx1 = -1, by1 = -1, bx2 = 1, by2 = 1
- Output:
- 100
- Explanation
- B lies completely inside A, so the covered area is just A's 10 * 10 = 100.
Example 3
- Input:
- ax1 = 0, ay1 = 0, ax2 = 2, ay2 = 3, bx1 = 2, by1 = 0, bx2 = 5, by2 = 3
- Output:
- 15
- Explanation
- The rectangles share the vertical edge x = 2, which has no area, so the total is 6 + 9 = 15.
Constraints
-10^4 <= ax1 <= ax2 <= 10^4-10^4 <= ay1 <= ay2 <= 10^4-10^4 <= bx1 <= bx2 <= 10^4-10^4 <= by1 <= by2 <= 10^4