223. Rectangle Area
Problem Description
You are given two rectangles on a 2D plane. Each rectangle is axis-aligned (meaning their sides are parallel to the x and y axes). Your task is to find the total area covered by both rectangles combined.
Each rectangle is defined by two points:
- The first rectangle has its bottom-left corner at
(ax1, ay1)
and its top-right corner at(ax2, ay2)
- The second rectangle has its bottom-left corner at
(bx1, by1)
and its top-right corner at(bx2, by2)
The key challenge is that the two rectangles might overlap. If they do overlap, you need to count the overlapping area only once in your total.
The solution approach calculates:
- The area of the first rectangle:
a = (ax2 - ax1) * (ay2 - ay1)
- The area of the second rectangle:
b = (bx2 - bx1) * (by2 - by1)
- The overlapping area by finding:
- The overlapping width:
width = min(ax2, bx2) - max(ax1, bx1)
- The overlapping height:
height = min(ay2, by2) - max(ay1, by1)
- If either width or height is negative, there's no overlap, so we use
max(width, 0)
andmax(height, 0)
- The overlapping width:
- The final answer:
a + b - (overlapping area)
The formula a + b - max(height, 0) * max(width, 0)
adds both rectangle areas and subtracts the overlap to avoid double-counting.
Intuition
When we need to find the total area covered by two rectangles, the natural first thought is to simply add their individual areas. However, this creates a problem: if the rectangles overlap, we're counting that overlapping region twice.
Think of it like laying two pieces of paper on a table. If they overlap, the overlapping part shouldn't be counted twice when measuring the total covered area. So we need to subtract the overlap once from our sum.
To find if and where rectangles overlap, we can observe that:
- For two rectangles to overlap horizontally, the left edge of the overlap must be at
max(ax1, bx1)
(the rightmost of the two left edges) - The right edge of the overlap must be at
min(ax2, bx2)
(the leftmost of the two right edges) - Similarly for vertical overlap: bottom at
max(ay1, by1)
and top atmin(ay2, by2)
This gives us the overlapping width as min(ax2, bx2) - max(ax1, bx1)
and height as min(ay2, by2) - max(ay1, by1)
.
Here's the clever insight: if the rectangles don't overlap, one or both of these values will be negative! For example, if rectangle A is completely to the left of rectangle B, then min(ax2, bx2)
(A's right edge) will be less than max(ax1, bx1)
(B's left edge), giving a negative width.
Since negative dimensions don't make sense for an area, we use max(0, width)
and max(0, height)
to handle both overlapping and non-overlapping cases elegantly. When there's no overlap, this becomes zero, and when there is overlap, we get the correct overlapping area.
The final formula becomes: area1 + area2 - overlapping_area
Solution Approach
The implementation follows a straightforward calculation approach based on geometric properties:
Step 1: Calculate Individual Rectangle Areas
First, we calculate the area of each rectangle using the standard formula:
- Rectangle A area:
a = (ax2 - ax1) * (ay2 - ay1)
- Rectangle B area:
b = (bx2 - bx1) * (by2 - by1)
Step 2: Find the Overlapping Region Dimensions
To determine if and where the rectangles overlap, we calculate:
-
Overlapping width:
width = min(ax2, bx2) - max(ax1, bx1)
max(ax1, bx1)
gives us the x-coordinate where the overlap starts (the rightmost left edge)min(ax2, bx2)
gives us the x-coordinate where the overlap ends (the leftmost right edge)
-
Overlapping height:
height = min(ay2, by2) - max(ay1, by1)
max(ay1, by1)
gives us the y-coordinate where the overlap starts (the topmost bottom edge)min(ay2, by2)
gives us the y-coordinate where the overlap ends (the bottommost top edge)
Step 3: Handle Non-Overlapping Cases
If the rectangles don't overlap:
- Either
width
orheight
(or both) will be negative - We use
max(width, 0)
andmax(height, 0)
to convert negative values to 0 - This ensures the overlapping area becomes 0 when there's no overlap
Step 4: Calculate Total Area
The final formula combines everything:
total_area = a + b - max(height, 0) * max(width, 0)
This adds both rectangle areas and subtracts the overlapping area (if any) to avoid double-counting.
The beauty of this approach is its simplicity - it handles all cases (overlapping, non-overlapping, touching edges) with a single unified formula, without needing conditional statements to check different scenarios.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through a concrete example to illustrate the solution approach.
Example: We have two rectangles:
- Rectangle A: bottom-left at (0, 0) and top-right at (3, 3)
- Rectangle B: bottom-left at (2, 1) and top-right at (5, 4)
Let's visualize this on a coordinate grid:
4 | . . B B B 3 | A A A B B B 2 | A A A B B B 1 | A A A B B . 0 | A A A . . . +--------------- 0 1 2 3 4 5
Step 1: Calculate Individual Rectangle Areas
- Rectangle A area:
a = (3 - 0) * (3 - 0) = 3 * 3 = 9
- Rectangle B area:
b = (5 - 2) * (4 - 1) = 3 * 3 = 9
Step 2: Find the Overlapping Region Dimensions
For the overlapping width:
- The rightmost left edge:
max(0, 2) = 2
(Rectangle B's left edge is further right) - The leftmost right edge:
min(3, 5) = 3
(Rectangle A's right edge is further left) - Overlapping width:
3 - 2 = 1
For the overlapping height:
- The topmost bottom edge:
max(0, 1) = 1
(Rectangle B's bottom edge is higher) - The bottommost top edge:
min(3, 4) = 3
(Rectangle A's top edge is lower) - Overlapping height:
3 - 1 = 2
The overlapping region is from (2, 1) to (3, 3), which you can see in the grid where both A and B markers would appear.
Step 3: Calculate Overlapping Area
- Since both width (1) and height (2) are positive, we have an overlap
- Overlapping area:
max(1, 0) * max(2, 0) = 1 * 2 = 2
Step 4: Calculate Total Area
- Total area =
9 + 9 - 2 = 16
We can verify this by counting the grid cells: Rectangle A covers 9 cells, Rectangle B covers 9 cells, but 2 cells are counted twice (the overlap at positions (2,1) and (2,2)), so the total unique area is 16 cells.
Non-overlapping Example: If Rectangle B were at bottom-left (4, 0) and top-right (6, 2):
- Overlapping width:
min(3, 6) - max(0, 4) = 3 - 4 = -1
- Since width is negative,
max(-1, 0) = 0
- Overlapping area:
0 * max(height, 0) = 0
- Total area:
9 + 4 - 0 = 13
(no overlap to subtract)
Solution Implementation
1class Solution:
2 def computeArea(
3 self,
4 ax1: int,
5 ay1: int,
6 ax2: int,
7 ay2: int,
8 bx1: int,
9 by1: int,
10 bx2: int,
11 by2: int,
12 ) -> int:
13 # Calculate area of rectangle A
14 # Rectangle A has bottom-left corner (ax1, ay1) and top-right corner (ax2, ay2)
15 area_rectangle_a = (ax2 - ax1) * (ay2 - ay1)
16
17 # Calculate area of rectangle B
18 # Rectangle B has bottom-left corner (bx1, by1) and top-right corner (bx2, by2)
19 area_rectangle_b = (bx2 - bx1) * (by2 - by1)
20
21 # Calculate the overlap dimensions between the two rectangles
22 # For overlap to exist, the rectangles must intersect both horizontally and vertically
23
24 # Find the width of the overlapping region
25 # The overlap starts at the rightmost left edge and ends at the leftmost right edge
26 overlap_width = min(ax2, bx2) - max(ax1, bx1)
27
28 # Find the height of the overlapping region
29 # The overlap starts at the topmost bottom edge and ends at the bottommost top edge
30 overlap_height = min(ay2, by2) - max(ay1, by1)
31
32 # Calculate the overlapping area
33 # If either dimension is negative, there's no overlap, so we use max with 0
34 overlap_area = max(overlap_height, 0) * max(overlap_width, 0)
35
36 # Total area = Area of A + Area of B - Overlapping area
37 # We subtract the overlap to avoid counting it twice
38 return area_rectangle_a + area_rectangle_b - overlap_area
39
1class Solution {
2 /**
3 * Computes the total area covered by two rectangles in a 2D plane.
4 * Each rectangle is defined by its bottom-left and top-right corners.
5 *
6 * @param ax1 x-coordinate of the bottom-left corner of rectangle A
7 * @param ay1 y-coordinate of the bottom-left corner of rectangle A
8 * @param ax2 x-coordinate of the top-right corner of rectangle A
9 * @param ay2 y-coordinate of the top-right corner of rectangle A
10 * @param bx1 x-coordinate of the bottom-left corner of rectangle B
11 * @param by1 y-coordinate of the bottom-left corner of rectangle B
12 * @param bx2 x-coordinate of the top-right corner of rectangle B
13 * @param by2 y-coordinate of the top-right corner of rectangle B
14 * @return The total area covered by both rectangles
15 */
16 public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
17 // Calculate the area of rectangle A
18 int areaRectangleA = (ax2 - ax1) * (ay2 - ay1);
19
20 // Calculate the area of rectangle B
21 int areaRectangleB = (bx2 - bx1) * (by2 - by1);
22
23 // Calculate the width of the overlapping region
24 // If no overlap, this will be negative
25 int overlapWidth = Math.min(ax2, bx2) - Math.max(ax1, bx1);
26
27 // Calculate the height of the overlapping region
28 // If no overlap, this will be negative
29 int overlapHeight = Math.min(ay2, by2) - Math.max(ay1, by1);
30
31 // Calculate the overlapping area
32 // Use Math.max to ensure non-negative values (0 if no overlap)
33 int overlapArea = Math.max(overlapHeight, 0) * Math.max(overlapWidth, 0);
34
35 // Total area = Area A + Area B - Overlapping area
36 return areaRectangleA + areaRectangleB - overlapArea;
37 }
38}
39
1class Solution {
2public:
3 int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
4 // Calculate the area of the first rectangle
5 int areaRectangleA = (ax2 - ax1) * (ay2 - ay1);
6
7 // Calculate the area of the second rectangle
8 int areaRectangleB = (bx2 - bx1) * (by2 - by1);
9
10 // Calculate the width of the overlapping region
11 // The overlap starts at the maximum of the left edges
12 // and ends at the minimum of the right edges
13 int overlapWidth = min(ax2, bx2) - max(ax1, bx1);
14
15 // Calculate the height of the overlapping region
16 // The overlap starts at the maximum of the bottom edges
17 // and ends at the minimum of the top edges
18 int overlapHeight = min(ay2, by2) - max(ay1, by1);
19
20 // Calculate the area of overlap
21 // If width or height is negative (no overlap), max() ensures we get 0
22 int overlapArea = max(overlapHeight, 0) * max(overlapWidth, 0);
23
24 // Total area = sum of both rectangles minus the overlapping area
25 return areaRectangleA + areaRectangleB - overlapArea;
26 }
27};
28
1/**
2 * Computes the total area covered by two rectangles, accounting for any overlap.
3 * Uses the inclusion-exclusion principle: Total Area = Area1 + Area2 - Overlap Area
4 *
5 * @param ax1 - X-coordinate of the bottom-left corner of rectangle A
6 * @param ay1 - Y-coordinate of the bottom-left corner of rectangle A
7 * @param ax2 - X-coordinate of the top-right corner of rectangle A
8 * @param ay2 - Y-coordinate of the top-right corner of rectangle A
9 * @param bx1 - X-coordinate of the bottom-left corner of rectangle B
10 * @param by1 - Y-coordinate of the bottom-left corner of rectangle B
11 * @param bx2 - X-coordinate of the top-right corner of rectangle B
12 * @param by2 - Y-coordinate of the top-right corner of rectangle B
13 * @returns The total area covered by both rectangles
14 */
15function computeArea(
16 ax1: number,
17 ay1: number,
18 ax2: number,
19 ay2: number,
20 bx1: number,
21 by1: number,
22 bx2: number,
23 by2: number,
24): number {
25 // Calculate the area of rectangle A
26 const areaA: number = (ax2 - ax1) * (ay2 - ay1);
27
28 // Calculate the area of rectangle B
29 const areaB: number = (bx2 - bx1) * (by2 - by1);
30
31 // Calculate the width of the overlapping region
32 // The overlap starts at the maximum of the left edges and ends at the minimum of the right edges
33 const overlapWidth: number = Math.min(ax2, bx2) - Math.max(ax1, bx1);
34
35 // Calculate the height of the overlapping region
36 // The overlap starts at the maximum of the bottom edges and ends at the minimum of the top edges
37 const overlapHeight: number = Math.min(ay2, by2) - Math.max(ay1, by1);
38
39 // Calculate the overlapping area
40 // If either dimension is negative (no overlap), the result will be 0
41 const overlapArea: number = Math.max(overlapWidth, 0) * Math.max(overlapHeight, 0);
42
43 // Return the total area using inclusion-exclusion principle
44 return areaA + areaB - overlapArea;
45}
46
Time and Space Complexity
The time complexity is O(1)
because the algorithm performs a fixed number of arithmetic operations regardless of the input values. It calculates:
- Two rectangle areas using multiplication:
(ax2 - ax1) * (ay2 - ay1)
and(bx2 - bx1) * (by2 - by1)
- The overlap width using
min(ax2, bx2) - max(ax1, bx1)
- The overlap height using
min(ay2, by2) - max(ay1, by1)
- The final result with one subtraction and multiplication
All these operations take constant time.
The space complexity is O(1)
because the algorithm only uses a fixed amount of extra space to store the intermediate variables a
, b
, width
, and height
, regardless of the input values. No additional data structures that scale with input size are created.
Common Pitfalls
1. Incorrectly Calculating Overlap When Rectangles Don't Intersect
The Pitfall:
A common mistake is forgetting to handle the case where rectangles don't overlap. When calculating overlap_width = min(ax2, bx2) - max(ax1, bx1)
or overlap_height = min(ay2, by2) - max(ay1, by1)
, these values can be negative when rectangles are completely separated. If you directly multiply negative width and height values, you might get a positive overlap area, which is incorrect.
Example of Wrong Implementation:
# WRONG: This doesn't handle non-overlapping rectangles
overlap_area = (min(ax2, bx2) - max(ax1, bx1)) * (min(ay2, by2) - max(ay1, by1))
# If width = -5 and height = -3, this gives overlap_area = 15 (incorrect!)
The Solution:
Always use max(value, 0)
to ensure negative dimensions become zero:
overlap_area = max(overlap_height, 0) * max(overlap_width, 0)
2. Integer Overflow in Large Coordinate Values
The Pitfall:
When dealing with very large coordinate values (near the limits of integer range), calculating areas might cause integer overflow. For instance, if coordinates are close to 10^9, the area calculation (ax2 - ax1) * (ay2 - ay1)
could exceed standard integer limits in some languages.
The Solution: In Python, this is handled automatically as integers can be arbitrarily large. However, in other languages like Java or C++, you might need to:
- Use long/long long data types instead of int
- Be cautious about the order of operations
- Consider breaking calculations into smaller steps if needed
3. Confusing Coordinate System Orientation
The Pitfall: Developers sometimes mix up which corner is which, especially when dealing with different coordinate system conventions. The problem states that we have bottom-left and top-right corners, meaning:
x1 < x2
(left to right)y1 < y2
(bottom to top)
If you accidentally treat (x1, y1) as top-left instead of bottom-left, your calculations will be wrong.
The Solution: Always verify your understanding of the coordinate system before implementing. Draw a quick diagram if needed, and ensure you're consistent with the problem's specification that (x1, y1) is bottom-left and (x2, y2) is top-right.
4. Edge Case: Rectangles Sharing Only a Border
The Pitfall:
When rectangles share only an edge or a corner (touching but not overlapping), the overlap calculation might seem ambiguous. For example, if ax2 == bx1
, the rectangles touch but don't overlap.
The Solution:
The formula min(ax2, bx2) - max(ax1, bx1)
naturally handles this case by producing zero for the overlapping dimension, which is mathematically correct since a line or point has zero area. No special handling is needed, but it's important to understand that the solution correctly treats touching rectangles as having zero overlap area.
Which of the tree traversal order can be used to obtain elements in a binary search tree in sorted order?
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!