Editor

Overlap of Two Rectangles

#262 · Geometry · Intermediate · 55 XP · about 8 min

Two rugs lie on a floor, both with their sides parallel to the walls. Each is given as a tuple (x1, y1, x2, y2) of integers: (x1, y1) is its bottom-left corner and (x2, y2) its top-right corner, so x1 < x2 and y1 < y2.

Write overlap_area(a, b) that returns the area of floor covered by both rugs, as an integer. Rugs that only touch along an edge or at a corner overlap by 0, and so do rugs that do not touch at all.

Examples

overlap_area((0, 0, 4, 3), (2, 1, 6, 5))     # returns 4
overlap_area((0, 0, 2, 2), (2, 0, 4, 2))     # returns 0
overlap_area((0, 0, 10, 10), (3, 3, 5, 6))   # returns 6

In the first example the shared part runs from x = 2 to x = 4 and from y = 1 to y = 3: a 2 by 2 square with area 4. In the second the rugs share only an edge.

Constraints

  • Coordinates are integers between -109 and 109.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.