Site icon Study Algorithms

Determine if 2 rectangles overlap

Question: You are given two axis-aligned rectangles. You have to determine if these rectangles overlap each other or not.
Rectangle 1 : P1 (x, y), P2 (x,y)
Rectangle 2 : P3 (x,y), P4 (x,y)

In this problem statement, we are given co-ordinates for 2 rectangles and we have to determine if they overlap or not. In a way we can say that our use case looks like this.


At the first glance, the problem seems to look very complicated. If you are coming up with a complicated set of conditionals, you might think too hard. There is an easier way. Try to think in the opposite direction.

Assume that the two rectangles are given as point (P1, P2) and (P3, P4) respectively. One direct way to attempt this problem is when two rectangles overlap, one rectangle’s corner point(s) must contain in the other rectangle. Do keep in mind of the following cases:


When we look at the problem now, it seems to get more complicated because of the 8 conditional statements which seem to be necessary immediately. Can we simplify it further?

YES, by using the negation method.

Do you remember the probability questions where you have to determine the chance such that no black ball comes out of a bag having 7 different color balls? We find the probability of black ball and then subtract it from 1 to get the result.

Similarly, A much easier and better approach would be to think from the opposite. How about asking yourself how the two rectangles cannot overlap each other? Two rectangles do not overlap when one is above/below, or to the left/right of the other rectangle.
So, when we try to workout the expression we get:

! ( P2.y < P3.y || P1.y > P4.y || P2.x < P3.x || P1.x > P4.x )

This can be simplified further using De Morgan’s law:-

( P2.y <= P3.y && P1.y >= P4.y && P2.x >= P3.x && P1.x <= P4.x )

Pretty neat!!!

Exit mobile version