Problem
Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don’t intersect, return 0.
Examples
Example 1
|
|
Solution
Method 1 - Coordinate Geometry
To find the area of the intersection of two rectangles:
- Determine the x and y ranges of each rectangle.
- Compute the overlapping range on the x-axis and the y-axis.
- Calculate the intersection area by finding the width and height of the overlapping range. If there is no overlap, the intersection area is 0.
Approach
- Determine Rectangle Edges:
- For each rectangle, compute the coordinates of the bottom-right corner using the top-left corner and the dimensions.
- Compute Overlapping Range:
- Find the overlapping range on the x-axis by determining the maximum of the left edges and the minimum of the right edges.
- Find the overlapping range on the y-axis by determining the maximum of the bottom edges and the minimum of the top edges.
- Calculate Intersection Area:
- If the overlapping width and height are positive, multiply them to get the intersection area.
- If either width or height is zero or negative, there is no intersection.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
because the solution involves basic arithmetic computations that take constant time. - 🧺 Space complexity:
O(1)
since no additional space is required.