---
# System prepended metadata

title: '[223. Rectangle Area](https://leetcode.com/problems/rectangle-area/)'
tags: [Geometry, leetcode, Math, Medium]

---

###### tags: `leetcode` `Medium` `Math` `Geometry`
# [223. Rectangle Area](https://leetcode.com/problems/rectangle-area/)

## Description

Given the coordinates of two **rectilinear** rectangles in a 2D plane, return the total area covered by the two rectangles.  

The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`.  

The second rectangle is defined by its **bottom-left** corner `(bx1, by1)` and its **top-right** corner `(bx2, by2)`.

## Examples
### Example 1:

![Rectangle Area](https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png)
**Input**: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
**Output**: 45

### Example 2:

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

## Constraints:

- $-10^4\leq ax1\leq ax2\leq 10^4$
- $-10^4\leq ay1\leq ay2\leq 10^4$
- $-10^4\leq bx1\leq bx2\leq 10^4$
- $-10^4\leq by1\leq by2\leq 10^4$

## Code

```c=
#define Square(x1, x2, y1, y2) ((x2 - x1) * (y2 - y1))
#define Large1(a1, b1) (a1 < b1 ? b1 : a1)
#define Min2(a2, b2) (a2 < b2 ? a2 : b2)

int CrossDistance(int a1, int a2, int b1, int b2) {
    if ((b1 > a2) || (a1 > b2))
        return 0;
    return Min2(a2, b2) - Large1(a1, b1);
}

int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
    return Square(ax1, ax2, ay1, ay2) + Square(bx1, bx2, by1, by2) -
           CrossDistance(ax1, ax2, bx1, bx2) * CrossDistance(ay1, ay2, by1, by2);
}
```

## Complexity

|Space |Time  |
|-     |-     |
|$O(1)$|$O(1)$|

## Result

- Runtime: 4 ms, 85.71%
- Memory Usage: 5.6 MB, 42.86%
