Rectangle Area — LeetCode 223 Python Solution

MediumGeometryMath
Problem
#223
Reading time
3 min

The problem

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

Example

Input
ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output
45

Python solution

Python
class Solution:
    def computeArea(
        self,
        ax1: int,
        ay1: int,
        ax2: int,
        ay2: int,
        bx1: int,
        by1: int,
        bx2: int,
        by2: int,
    ) -> int:
        a = (ax2 - ax1) * (ay2 - ay1)
        b = (bx2 - bx1) * (by2 - by1)
        width = min(ax2, bx2) - max(ax1, bx1)
        height = min(ay2, by2) - max(ay1, by1)
        return a + b - max(height, 0) * max(width, 0)

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 223. Rectangle Area is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Geometry.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 223. Rectangle Area?
LeetCode 223. Rectangle Area is rated Medium on LeetCode.
What is the time complexity of LeetCode 223. Rectangle Area?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 223. Rectangle Area?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 223. Rectangle Area cover?
LeetCode 223. Rectangle Area is tagged Geometry and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview