Finding the area of intersection of two rectangles

 

Here is something I tried solving on the train while "whiteboarding" it in excalidraw on my phone.

Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don't intersect, return 0.

Here is the complete problem -

Understanding the problem

Given the example above we can plot the rectangle in the following diagram, and it is then easy to visually determine the points of intersection and arrive at the area

    3 * 2 = 6

The example makes it seem easy to arrive at a simple equation. But, what about other scenarios.

We really, need to determine the co-ordinates on both axes where the intersection or overlap happen. The 4 co-ordinates will help us solve for width and height, and thus area.

Width

Let's consider the X axis.

If we think about this more, we are trying to make a choice between X1 and Xa, and between X2 and Xb.

Height

We can apply the logic for the width to the height too.

Calculating Area

This is the easy part since we know both values of Xi and Xj , along with Yi and Yj we can now calculate width and height and thus area.

But, we do have to confirm that the rectangles overlap. This can be done by comparing 

  • Xi to Xj
    • If Xi is greater than Xj, these co-ordinates cannot overlap because Xi is on the right side of Xj
  • Yi to Yj
    • If Yi is less than Yj, these co-ordinates cannot overlap because Yi is below Yj

Notes

It is easy to mix up when to apply Min or Max to the co-ordinates for a simple problem like this, and I find it easy to draw an example. You'll find that choosing the right function becomes a lot simpler, including arriving at the how to determine if the rectangles do not overlap