Geometry
Intersection
Rectangles
Math
ComputationalGeometry

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.

Practice algorithms

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:

 
A.x2 <= B.x1  OR  A.x1 >= B.x2  OR  A.y2 <= B.y1  OR  A.y1 >= B.y2

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:

 
area = (right - left) * (top - bottom)

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

python
1def rectangle_intersection(a, b):
2    """
3    Each rectangle is a tuple (x1, y1, x2, y2).
4    Returns the intersection rectangle and its area, or None if no overlap.
5    """
6    left = max(a[0], b[0])
7    bottom = max(a[1], b[1])
8    right = min(a[2], b[2])
9    top = min(a[3], b[3])
10
11    if left < right and bottom < top:
12        area = (right - left) * (top - bottom)
13        return (left, bottom, right, top), area
14    return None, 0
15
16
17# Example
18a = (0, 0, 4, 4)
19b = (2, 2, 6, 6)
20rect, area = rectangle_intersection(a, b)
21print(f"Intersection: {rect}, Area: {area}")
22# Output: Intersection: (2, 2, 4, 4), Area: 4

C++ Implementation

cpp
1#include <iostream>
2#include <algorithm>
3
4struct Rect {
5    int x1, y1, x2, y2;
6};
7
8bool intersect(const Rect& a, const Rect& b, Rect& result) {
9    result.x1 = std::max(a.x1, b.x1);
10    result.y1 = std::max(a.y1, b.y1);
11    result.x2 = std::min(a.x2, b.x2);
12    result.y2 = std::min(a.y2, b.y2);
13    return result.x1 < result.x2 && result.y1 < result.y2;
14}
15
16int main() {
17    Rect a = {0, 0, 4, 4};
18    Rect b = {2, 2, 6, 6};
19    Rect result;
20    if (intersect(a, b, result)) {
21        int area = (result.x2 - result.x1) * (result.y2 - result.y1);
22        std::cout << "Area: " << area << std::endl; // Output: 4
23    }
24    return 0;
25}

Java Implementation

java
1public class RectIntersection {
2    public static int[] intersect(int[] a, int[] b) {
3        int left = Math.max(a[0], b[0]);
4        int bottom = Math.max(a[1], b[1]);
5        int right = Math.min(a[2], b[2]);
6        int top = Math.min(a[3], b[3]);
7
8        if (left < right && bottom < top) {
9            return new int[]{left, bottom, right, top};
10        }
11        return null; // no intersection
12    }
13
14    public static void main(String[] args) {
15        int[] a = {0, 0, 4, 4};
16        int[] b = {2, 2, 6, 6};
17        int[] result = intersect(a, b);
18        if (result != null) {
19            int area = (result[2] - result[0]) * (result[3] - result[1]);
20            System.out.println("Area: " + area); // Output: 4
21        }
22    }
23}

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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.