# Find if two rectangles overlap using C++.

We know that a rectangle can be represented using two coordinates, the top left corner, and the bottom right corner. Suppose there are two rectangles, we have to check whether these two overlap or not. There are four coordinate points (l1, r1) and (l2, r2).

• l1 is the top-left corner of first rectangle
• r1 is the bottom-right corner of the first rectangle
• l2 is the top-left corner of second rectangle
• r2 is the bottom-right corner of the second rectangle

We have assumed that the rectangles are parallel to the coordinate axes. To solve this, we have to check a few conditions.

• One rectangle is above the top edge of another rectangle
• One rectangle is on the left side of the left edge of another rectangle.

## Example

Live Demo

#include<iostream>
using namespace std;
class Point {
public:
int x, y;
};
bool isOverlapping(Point l1, Point r1, Point l2, Point r2) {
if (l1.x > r2.x || l2.x > r1.x)
return false;
if (l1.y < r2.y || l2.y < r1.y)
return false;
return true;
}
int main() {
Point l1 = {0, 10}, r1 = {10, 0};
Point l2 = {5, 5}, r2 = {15, 0};
if (isOverlapping(l1, r1, l2, r2))
cout << "Rectangles are Overlapping";
else
cout << "Rectangles are not Overlapping";
}

## Output

Rectangles are Overlapping

Updated on: 30-Oct-2019

675 Views