Similar Problems
Similar Problems not available
Rectangle Area - Leetcode Solution
Companies:
LeetCode: Rectangle Area Leetcode Solution
Difficulty: Medium
Topics: math
The Rectangle Area problem on LeetCode is a mathematical problem that involves finding the area of two overlapping rectangles.
The problem statement reads as follows:
"Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner coordinates."
The input is given in the form of four integers: the coordinates of the bottom left corner and top right corner of the two rectangles. The output is the total area covered by the two rectangles.
Example:
Input:
rectangle1 = [-3, 0, 3, 4]
rectangle2 = [0, -1, 9, 2]
Output:
45
To solve this problem, the first step is to calculate the area of each rectangle separately. This can be done by finding the difference between the x-coordinates and y-coordinates of the bottom left and top right corners of each rectangle.
Next, we need to check if the two rectangles overlap. To do this, we need to compare the x-coordinates and y-coordinates of the rectangles and see if they intersect.
If the rectangles intersect, we need to find the area of the intersection. This can be done by finding the x-coordinate and y-coordinate of the bottom left corner and top right corner of the intersection rectangle.
Now, we can calculate the total area covered by the two rectangles by subtracting the area of the intersection rectangle from the sum of the areas of the two rectangles.
Here is the Python code to solve the Rectangle Area problem on LeetCode:
class Solution:
def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
# Calculate the area of each rectangle
area1 = (C - A) * (D - B)
area2 = (G - E) * (H - F)
# Check if the two rectangles intersect
x_overlap = max(0, min(C, G) - max(A, E))
y_overlap = max(0, min(D, H) - max(B, F))
overlap_area = x_overlap * y_overlap
# Calculate the total area covered by the two rectangles
total_area = area1 + area2 - overlap_area
return total_area
In the above code, we define a class called Solution and a method called computeArea. The method takes in the coordinates of the two rectangles as input and returns the total area covered by the two rectangles.
First, we calculate the area of each rectangle separately. Next, we calculate the overlap area by finding the x-coordinate and y-coordinate of the intersection rectangle. We use the max and min functions to find the x-coordinate and y-coordinate of the bottom left and top right corners of the intersection rectangle.
Finally, we calculate the total area covered by the two rectangles by subtracting the overlap area from the sum of the areas of the two rectangles. We return the total area as output.
Rectangle Area Solution Code
1