Algorithm to check if two boxes overlap
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Detecting whether two boxes overlap is a fundamental problem in computer science, especially useful in areas such as computer graphics, collision detection in physics engines, and geographical information systems. In this article, we'll explore an algorithmic approach to solve the problem of determining if two two-dimensional boxes overlap.
The Axis-Aligned Bounding Box (AABB) Overlap Algorithm
The most straightforward type of boxes we often encounter in programming problems are the Axis-Aligned Bounding Boxes (AABB). AABB is a rectangular box aligned with the coordinate axes, which simplifies calculations greatly.
Problem Statement
Given two rectangles (let’s denote them as `Box A` and `Box B`), each defined by the coordinates of their lower-left and upper-right corners:
• `Box A`: and • `Box B`: and
The task is to determine if these two boxes overlap.
Overlap Conditions
Two boxes do not overlap only if one is completely to the left, right, above, or below the other. Therefore, we can conclude there’s an overlap if and only if:
- The right edge of `Box A` is greater than or equal to the left edge of `Box B`.
- The left edge of `Box A` is less than or equal to the right edge of `Box B`.
- The top edge of `Box A` is greater than or equal to the bottom edge of `Box B`.
- The bottom edge of `Box A` is less than or equal to the top edge of `Box B`.
These conditions can be expressed as:
If all conditions are true, the boxes overlap.
Algorithm in Pseudocode
• `Box A`: Bottom-left corner (1, 1), Top-right corner (3, 3). • `Box B`: Bottom-left corner (2, 2), Top-right corner (5, 5). • Collision Detection: Common in gaming and simulation engines to detect when entities (represented as bounding boxes) contact each other. • Geographical Overlay Analysis: In mapping systems to determine overlapping regions of interest.

