# Check if two rectangles overlap

Given two rectangles ra and rb , check if they overlap. In other words, if they have common area or not. This is most asked interview questions in biggies like FB, Google, Amazon and MS.

Structure of the rectangle is :

```struct rectangle
{
int topx;
int topy;
int botx;
int boty;
};
```

This questions was asked in Amazon written test.

Approach : Two rectangles A and B don’t overlap if one of these is true.

1. left edge of A is to the right of right edge of B.
2. right edge of A is to the left of left edge of B.
3. Top edge of A is below bottom edge of B.
4. Bottom edge of A is above top edge of B.

i.e. ra.topx > rb.botx || ra.botx < rb.topx || ra.topy > rb.boty || ra.boty < rb.topy

They will overlap if all of above conditions are false.

```isOverlap(struct rect ra,struct rect rb)
{
bool noOverlap = (ra.topx > rb.botx || ra.botx < rb.topx
|| ra.topy > rb.boty || ra.boty < rb.topy);

return !noOverLap;
}
```

### 0 Thoughts on “Check if two rectangles overlap”

1. Sridhar on July 1, 2016 at 6:04 pm said:

Hi,
This solution is only true if the rectangle’s sides are parallel to the x and y axes?