How much do two rectangles overlap?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Understanding the overlap between two rectangles is a fundamental problem in computational geometry, with applications ranging from computer graphics to geographic information systems and collision detection in video games. This article explains how to determine the overlap area between two axis-aligned rectangles, provides formulas, and walks through concrete examples.
Defining Axis-Aligned Rectangles
An axis-aligned rectangle has edges parallel to the coordinate axes. Each rectangle is defined by its top-left and bottom-right coordinates:
- Rectangle A: to
- Rectangle B: to
Where , for Rectangle A, and , for Rectangle B.
Detecting Overlap
For two rectangles to overlap, their projections on both the x-axis and the y-axis must intersect:
- In the x-dimension:
- In the y-dimension:
If both conditions hold, the rectangles overlap. If either condition fails, they do not.
Calculating the Overlapping Area
When the rectangles do overlap, the intersection forms another rectangle whose corners are:
- Left:
- Right:
- Top:
- Bottom:
The overlapping area is:
The terms ensure the result is zero when the rectangles do not overlap, making this a single formula that handles both cases.
Code Implementation
Worked Examples
Example 1: No Overlap
- Rectangle A: to
- Rectangle B: to
Check x-overlap: and . Since , there is no overlap.
Result:
Example 2: Partial Overlap
- Rectangle A: to
- Rectangle B: to
The intersection rectangle is to :
Example 3: Full Containment
- Rectangle A: to
- Rectangle B: to
The intersection is just Rectangle B itself:
Computing Intersection over Union (IoU)
In computer vision and object detection, the Intersection over Union metric is the standard way to quantify how much two bounding boxes overlap:
where and are the areas of the two rectangles. IoU ranges from 0 (no overlap) to 1 (identical rectangles).
Use Cases
Computer Graphics
In rendering pipelines, clipping algorithms need to detect visible regions by calculating the overlapping areas of bounding boxes. Only the overlapping portion needs to be rasterized.
Collision Detection
Physics engines use bounding box overlap as a fast first pass before more expensive polygon-level collision checks. If the bounding boxes do not overlap, the objects cannot collide.
Geographic Information Systems (GIS)
Overlap calculations determine intersecting land parcels, administrative regions, or sensor coverage areas for spatial analysis.
Summary
| Concept | Formula or Condition |
| Overlap exists | AND |
| Overlap area | |
| IoU |
Determining the overlap between two rectangles is both practical and elegant. The formula relies on simple min/max operations, runs in time, and generalizes naturally to higher dimensions by adding one overlap check per axis.

