Problem 223

Abstract / Summary

Calculate the total area covered by two rectangles that may overlap on a plane.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
19 lines | 601 bytes | submitted September 7, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (500k+ submissions).

Typical patterns to solve this problem:
  • Geometry
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.
written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.04 | σ = 1.73

Complexity Analysis

Time: constant
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
44 links | 29 authors | 10 languages

Videos

12 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

30 easy 12 medium
43 solutions   September 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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