You are given the coordinates of two rectilinear rectangles in a 2D plane. The first rectangle is defined by its bottom-left corner (A, B) and its top-right corner (C, D), while the second rectangle is defined by its bottom-left corner (E, F) and its top-right corner (G, H).
Write a function to compute the total area covered by both rectangles.
Example 1:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Example 2:
Input: A = -2, B = -2, C = 2, D = 2, E = -2, F = -2, G = 2, H = 2
Output: 16
def compute_area(A, B, C, D, E, F, G, H):
# Calculate area of the first rectangle
area1 = (C - A) * (D - B)
# Calculate area of the second rectangle
area2 = (G - E) * (H - F)
# Calculate the overlap boundaries
overlap_left = max(A, E)
overlap_right = min(C, G)
overlap_bottom = max(B, F)
overlap_top = min(D, H)
# Initialize overlap area
overlap_area = 0
# Check if the overlap forms a valid rectangle
if overlap_left < overlap_right and overlap_bottom < overlap_top:
overlap_area = (overlap_right - overlap_left) * (overlap_top - overlap_bottom)
# Calculate the total area
total_area = area1 + area2 - overlap_area
return total_area
# Example use cases
print(compute_area(-3, 0, 3, 4, 0, -1, 9, 2)) # Output: 45
print(compute_area(-2, -2, 2, 2, -2, -2, 2, 2)) # Output: 16
The time complexity of this algorithm is O(1) because it involves a constant number of arithmetic operations and comparisons regardless of the input values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?