0223. Rectangle Area

223. Rectangle Area #

Problem #

Find the total area covered by two rectilinear rectangles in a 2D plane.

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Note:

Assume that the total area is never beyond the maximum possible value of int.

Problem Summary #

Calculate the total area formed by the overlap of two rectilinear rectangles on a 2D plane. Each rectangle is represented by the coordinates of its bottom-left vertex and top-right vertex, as shown in the figure. Note: Assume that the rectangle area will not exceed the range of int.

Solution Approach #

  • Given the coordinates of two rectangles, find the total area covered by these two rectangles on the coordinate axes.
  • Geometry problem. Since there are only 2 rectangles, just follow the problem statement. First calculate the areas of the two rectangles separately, add them together, and then subtract the overlapping area of the two rectangles.

Code #


package leetcode

func computeArea(A int, B int, C int, D int, E int, F int, G int, H int) int {
	X0, Y0, X1, Y1 := max(A, E), max(B, F), min(C, G), min(D, H)
	return area(A, B, C, D) + area(E, F, G, H) - area(X0, Y0, X1, Y1)
}

func area(x0, y0, x1, y1 int) int {
	l, h := x1-x0, y1-y0
	if l <= 0 || h <= 0 {
		return 0
	}
	return l * h
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文