Python 0223.py
class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
if ax1 > bx1:
ax1, bx1 = bx1, ax1
ay1, by1 = by1, ay1
ax2, bx2 = bx2, ax2
ay2, by2 = by2, ay2
a = (ax2 - ax1) * (ay2 - ay1)
b = (bx2 - bx1) * (by2 - by1)
if ax2 <= bx1 or ax1 >= bx2 or ay2 <= by1 or ay1 >= by2:
return a + b
cx = max(ax1, bx1) - min(ax2, bx2)
cy = max(ay1, by1) - min(ay2, by2)
c = cx * cy
return a + b - c
Difficulty
and has an acceptance rate of about 50% (500k+ submissions).
Typical patterns to solve this problem:
- Geometry
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation calculates the combined area of two axis-aligned rectangles defined by opposite corners. It first normalizes the ordering of the rectangles, computes the individual areas, checks for overlap, determines the intersecting region when necessary, and finally returns the union area by subtracting the overlap from the sum of the individual areas.
Normalization of Input
The function begins by ensuring that the first rectangle starts to the left of the second one. This is achieved with a conditional block that swaps the x-coordinates and the corresponding y-coordinates as well as the opposite corners when the left-most x of the first rectangle exceeds that of the second.
if ax1 > bx1:
ax1, bx1 = bx1, ax1
ay1, by1 = by1, ay1
ax2, bx2 = bx2, ax2
ay2, by2 = by2, ay2
By performing this swap, subsequent comparisons can rely on a consistent left-to-right ordering, simplifying the overlap logic.
Individual Area Computation
After normalization, the areas of the two rectangles are calculated directly from their width and height.
a = (ax2 - ax1) * (ay2 - ay1)
b = (bx2 - bx1) * (by2 - by1)
These expressions handle cases where a rectangle may have zero width or height, yielding an area of zero without additional checks.
Early Exit for Non-Overlapping Rectangles
The next conditional determines whether the rectangles are completely separate. If any of the four separating conditions hold-one rectangle entirely to the left, right, above, or below the other-the function returns the sum of the individual areas.
if ax2 <= bx1 or ax1 >= bx2 or ay2 <= by1 or ay1 >= by2:
return a + b
This early return avoids unnecessary calculations when there is no intersection.
Intersection Dimensions
When overlap exists, the width and height of the intersecting region are derived by taking the difference between the farthest left edge and the nearest right edge for the x-dimension, and similarly for the y-dimension.
cx = max(ax1, bx1) - min(ax2, bx2)
cy = max(ay1, by1) - min(ay2, by2)
c = cx * cy
The use of max and min captures the overlapping extents regardless of which rectangle extends further in each direction. The multiplication yields the area of the overlap.
Final Union Area
The function concludes by subtracting the overlapping area from the total of the two individual areas, delivering the combined area covered by either rectangle.
return a + b - c
Edge Cases Handled
The algorithm gracefully manages several boundary conditions:
- Touching Edges - When rectangles share a side or a corner, the separating condition (
<=or>=) evaluates to true, leading to a return of the sum of the individual areas, correctly reflecting zero overlap. - Zero-Size Rectangles - If any rectangle collapses to a line or a point (width or height zero), its area contribution becomes zero, and the overlap calculation yields zero as well, preserving correctness.
- Complete Containment - When one rectangle lies entirely within the other, the overlap dimensions compute the full area of the inner rectangle, and the subtraction removes this duplicate area, resulting in the outer rectangle’s area as the union.
- Swapped Coordinates - The initial swap ensures that even if the input rectangles are provided in reverse order, the subsequent logic remains valid without additional branching.
Performance Optimizations
The implementation exhibits several efficiency-focused choices:
- Single Pass Normalization - By swapping all coordinate pairs in one conditional block, the code avoids multiple passes or repeated comparisons later in the algorithm.
- Early Return Path - Detecting non-overlap before any arithmetic related to the intersection eliminates unnecessary calculations, reducing execution time for disjoint inputs.
- Direct Arithmetic - All area and overlap calculations are performed with straightforward arithmetic operations, avoiding function calls or complex data structures.
- Minimal Variable Scope - Intermediate results (
a,b,cx,cy,c) are confined to the smallest necessary scope, allowing the interpreter to reclaim memory promptly.
ELI5 - Simplified Explanation
Imagine two rectangles made of paper sitting on a table. The first bit of code just makes sure the rectangles are lined up in a way that is easy to measure. After that, the code finds out how much space the first rectangle takes up by multiplying its width and height. Then it does the exact same thing to find the space for the second rectangle. Sometimes these two rectangles might overlap, which means they are sitting on top of each other. If they are far apart and not touching at all, the code just adds their sizes together. If they do overlap, the code figures out the size of the shared middle part. It takes the total space of both rectangles added together and subtracts the overlapping part so that the middle section is only counted once instead of twice.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | aylei | Rust | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| fengvyi | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| fengvyi | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 836: Rectangle Overlap
- problem 3025: Find the Number of Ways to Place People I
- problem 3027: Find the Number of Ways to Place People II
- problem 3047: Find the Largest Area of Square Inside Two Rectangles
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 166: Fraction to Recurring Decimal
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality