203/670

203. Rectangle Area

Medium

Two axis-aligned rectangles sit on an integer coordinate plane, and you must return the total area they cover together — overlapping ground is counted once, not twice.

The function receives eight integers: rectangle A is described by its bottom-left corner (ax1, ay1) and top-right corner (ax2, ay2), and rectangle B by (bx1, by1) and (bx2, by2). Return one integer, the area of the union of the two rectangles.

The whole game is computing the overlap correctly — including the cases where the rectangles merely touch, are disjoint, or one swallows the other.

Two rectangles and their overlapA = (−3, 0) to (3, 4), B = (0, −1) to (9, 2); the gold region from (0, 0) to (3, 2) is counted only once in the union.
ABA ∩ B

Example 1:

Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2

Output: 45

Explanation: A covers 6 × 4 = 24 and B covers 9 × 3 = 27. They overlap on the 3 × 2 = 6 region from (0, 0) to (3, 2), so the union is 24 + 27 − 6 = 45.

Example 2:

Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2

Output: 16

Explanation: The rectangles are identical, so the union is just one 4 × 4 square: 16.

Constraints:

  • -10⁴ ≤ ax1 ≤ ax2 ≤ 10⁴, -10⁴ ≤ ay1 ≤ ay2 ≤ 10⁴
  • -10⁴ ≤ bx1 ≤ bx2 ≤ 10⁴, -10⁴ ≤ by1 ≤ by2 ≤ 10⁴
  • Rectangles may be degenerate (zero width or height).

Hints:

Union = area(A) + area(B) − area(A ∩ B). The two individual areas are trivial; only the intersection needs thought.

The intersection of two axis-aligned rectangles is itself axis-aligned: its x-range is [max(ax1, bx1), min(ax2, bx2)] and its y-range is [max(ay1, by1), min(ay2, by2)].

If either of those ranges is empty (right end ≤ left end), the overlap is zero — clamping each side length with max(0, …) handles disjoint and touching rectangles without any special cases.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: A = (-3, 0) to (3, 4), B = (0, -1) to (9, 2)

Expected output: 45