Two rectangles sit on a flat grid with their sides parallel to the axes. Rectangle A has its lower-left corner at (ax1, ay1) and its upper-right corner at (ax2, ay2). Rectangle B has corners (bx1, by1) and (bx2, by2).
Return the area of the region covered by at least one of them. Where they overlap, count that part only once.
Example 1
Input: ax1 = -2, ay1 = -1, ax2 = 3, ay2 = 3, bx1 = 1, by1 = 0, bx2 = 6, by2 = 5 Output: 39 Why: 20 + 25, minus the 2 × 3 overlap
2 more examples and the constraints
Example 2
Input: ax1 = 0, ay1 = 0, ax2 = 2, ay2 = 2, bx1 = 3, by1 = 1, bx2 = 5, by2 = 4 Output: 10 Why: they do not touch: 4 + 6
Example 3
Input: ax1 = -4, ay1 = -4, ax2 = 4, ay2 = 4, bx1 = -1, by1 = -1, bx2 = 2, by2 = 1 Output: 64 Why: B lies inside A, so only A counts
Constraints
- −10,000 ≤ ax1 ≤ ax2 ≤ 10,000 and −10,000 ≤ ay1 ≤ ay2 ≤ 10,000
- −10,000 ≤ bx1 ≤ bx2 ≤ 10,000 and −10,000 ≤ by1 ≤ by2 ≤ 10,000
- A rectangle may have zero width or height
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sweep column by columnO(W)
- Both areas minus the overlapO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 20,000-wide rectangles | Verdict |
|---|---|---|---|
| Sweep column by column | O(W) | Passes; does the same sum many times | |
| Both areas minus the overlap | O(1) | Best; one formula |
W = distance from the leftmost to the rightmost edge, at most 20,000.
Edge cases to test
- No overlap. The shared width or height comes out zero or negative;
max(0, ...)makes the overlap 0. - Touching edges. Rectangles that share only a side or a corner have overlap 0, not a 1-wide strip.
- One inside the other. The overlap is the smaller rectangle, so the answer is the bigger area.
- A flat rectangle. Zero width or height means zero area; the formula still works.
Common mistakes
- Multiplying the raw differences without
max(0, ...): two negative sides give a positive overlap for rectangles that never meet. - Clamping only the product, not each side, which has the same bug.
- Returning the bounding box area, which also counts the empty corners.
How to talk through it
- 1Clarify. Are the sides parallel to the axes? Can a rectangle be flat? Does touching count as overlap?
- 2Name the idea. Union area = area A + area B − area of the overlap.
- 3Find the overlap per axis. In x it runs from the larger left edge to the smaller right edge; same in y.
- 4Clamp each side. Take max(0, ...) of the width and of the height before multiplying.
- 5Test out loud. Run the overlapping, the apart and the nested examples, and check 39, 10 and 64.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?