Two Rectangles intersection
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Detecting whether two axis-aligned rectangles overlap is one of the most common geometric operations in programming. You encounter it in collision detection for games, hit testing in user interfaces, and spatial queries in databases. Understanding the underlying math lets you solve these problems in constant time with just a handful of comparisons.
Representing Axis-Aligned Rectangles
Before checking for intersection, you need a consistent way to represent each rectangle. The most common representation uses two corners: the bottom-left point (x1, y1) and the top-right point (x2, y2), where x1 < x2 and y1 < y2. Some systems use (x, y, width, height) instead, but you can always convert to the two-corner form.
The Overlap Condition
The key insight is that it is easier to check when two rectangles do not overlap and then negate the result. Two rectangles fail to overlap when they are separated along at least one axis. Rectangle A is to the left of B, or to the right, or above, or below. In code, no overlap means:
Negating this gives the overlap condition: the rectangles intersect when none of those separations hold. This is the separating axis theorem applied to axis-aligned rectangles.
Computing the Intersection Rectangle
When two rectangles do overlap, the intersection itself is another rectangle. You compute its coordinates by taking the maximum of the left edges and the minimum of the right edges for each axis:
- Intersection left = max(A.x1, B.x1)
- Intersection right = min(A.x2, B.x2)
- Intersection bottom = max(A.y1, B.y1)
- Intersection top = min(A.y2, B.y2)
If the intersection right is greater than the intersection left and the intersection top is greater than the intersection bottom, the rectangles overlap and this defines the intersection rectangle. Otherwise there is no overlap.
Area Calculation
Once you have the intersection rectangle, the area is simply:
This is useful when you need the intersection over union (IoU) metric, which is the intersection area divided by the total area of both rectangles minus the intersection area.
Python Implementation
C++ Implementation
Java Implementation
Handling the No-Intersection Case
When the computed left exceeds the right or the computed bottom exceeds the top, the rectangles do not overlap. In this case you should return a sentinel value (null, None, or an empty optional) rather than a rectangle with negative dimensions. Callers should always check for this before using the result. Returning zero area alone is ambiguous because two rectangles can share an edge with zero overlap area.
Applications
- Collision detection: Game engines check bounding box overlaps as a fast first pass before doing expensive pixel-perfect or polygon collision tests.
- UI hit testing: Determining whether a click point (treated as a 1x1 rectangle) falls inside a button or widget.
- Spatial databases: R-tree indexes use rectangle intersection to prune search results during range queries.
- Computer vision: IoU calculations for object detection rely on rectangle intersection to score how well predicted bounding boxes match ground truth.
Common Pitfalls
- Confusing strict and non-strict inequalities: Use
<if touching edges should not count as overlap, and<=if they should. Be explicit about which convention your system uses. - Mixing up coordinate systems: Screen coordinates often have y increasing downward, while math coordinates have y increasing upward. Swapping y1 and y2 leads to wrong results.
- Forgetting to validate input: If x1 >= x2 or y1 >= y2, the rectangle is degenerate. Validate before computing intersections.
- Integer overflow on area calculation: When coordinates are large integers, multiplying width by height can overflow. Use 64-bit integers or check bounds first.
- Assuming rectangles are axis-aligned: This algorithm only works for axis-aligned rectangles. Rotated rectangles require the full separating axis theorem with projection onto multiple axes.
Summary
- Two axis-aligned rectangles overlap when they are not separated along either the x-axis or the y-axis.
- The intersection rectangle is computed using max of left edges, min of right edges, max of bottom edges, and min of top edges.
- If the computed width or height is non-positive, there is no intersection.
- The algorithm runs in O(1) time and is the foundation for collision detection, hit testing, and spatial indexing.
- Always be careful about coordinate system conventions and strict versus non-strict inequality comparisons.
Related reading
- Ultra symmetrical line algorithm?
- Unbiased random number generator using a biased one
- Understanding concept of Gaussian Mixture Models
- Understanding randomness
- Unfamiliar symbol in algorithm what does ∀ mean?
- Unique permutations with no mirrored or circular repetitions
- upper bound, lower bound
- Use .corr to get the correlation between two columns

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.