Nov 10, Leetcode 223. Rectangle Area- Beware Pitfalls

https://leetcode.com/problems/rectangle-area/
Language: Python — Time: 15 minutes
Full Code on Gitfront.iohttps://github.com/cswartzell

Deceptive in its simplicity. As presented, sum the area of two rectangles given coordinates. So simple that it should clue an interviewee in that there must be a trick; otherwise this is a trivial one line question. The problem is presented on Leetcode with the trap shown clearly: the rectangles can overlap.

I’d like to think I’d spot this case in an interview even if not so obviously presented. It’s a good lesson in the absolute importance to really consider the problem before jumping straight to coding. Without the clue, one might be tempted to “show off” by simply returning the area of the two rectangles without considering the obvious edge case.

The actual solution is nearly as trivial, we must simply check if there is an overlap, and if so subtract it so it’s area is not counted twice. I started with a series of symmetric if blocks to determine if one rectangle started after the other but before it’s end, for each of the two dimensions, and if so calculate this overlap. While only a few lines, knew there must be a far simpler way to do it in one go.

The neat answer is indeed pretty elegant;

“`overlap_X = max(min(ax2,bx2)-max(ax1,bx1), 0)“`

We simply determine the distance between the right most starting point, and left most end point, regardless of which rectangle either point comes from. However, we must catch that this would return a negative result for rectangles that do not overlap. We fix this by maxing this with zero, so we only retain positive overlaps. We do this for each axis. From there, we can compute this in a single line (if we are playing golf instead of writing clean code; more on this later):

“`return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) – ( (max(min(ax2,bx2)-max(ax1,bx1), 0)) * ((max(min(ay2,by2)-max(ay1,by1), 0)) )“`

Leave a comment