LeetCode 223: Rectangle Area Solution
Master LeetCode problem 223 (Rectangle Area), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To find the total area covered by two rectangles, we can first calculate the area of each rectangle separately using the formula: area = (x2 - x1) * (y2 - y1). Then, we need to find the overlapping area of the two rectangles. The overlapping area can be calculated by finding the intersection of the x and y ranges of the two rectangles. If the rectangles do not overlap, the overlapping area will be 0. Finally, we add the areas of the two rectangles and subtract the overlapping area to get the total area covered by the two rectangles.
Solution Code
class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int areaA = (ax2 - ax1) * (ay2 - ay1);
int areaB = (bx2 - bx1) * (by2 - by1);
int overlapWidth = Math.min(ax2, bx2) - Math.max(ax1, bx1);
int overlapHeight = Math.min(ay2, by2) - Math.max(ay1, by1);
int overlapArea = Math.max(overlapWidth, 0) * Math.max(overlapHeight, 0);
return areaA + areaB - overlapArea;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 223 (Rectangle Area)?
This page provides optimized solutions for LeetCode problem 223 (Rectangle Area) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 223 (Rectangle Area)?
The time complexity for LeetCode 223 (Rectangle Area) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 223 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 223 in Java, C++, or Python.