MEDIUM Math & Geometry
223. Rectangle Area
๐ Problem
Given the coordinates of two axis-aligned rectangles (rec1 and rec2), return the total area covered by the two rectangles.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Total area = area1 + area2 - overlap
- โ Overlap only if rectangles intersect on both axes
- โ X overlap = min(right1, right2) - max(left1, left2) (if positive)
- โ Y overlap = min(top1, top2) - max(bottom1, bottom2) (if positive)
- โ Overlap area = xOverlap * yOverlap (if both positive)
- โ Time: O(1), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขTotal area = area1 + area2 - overlap
- โขOverlap only if rectangles intersect on both axes
- โขX overlap = min(right1, right2) - max(left1, left2) (if positive)
Common Pitfalls
- โขY overlap = min(top1, top2) - max(bottom1, bottom2) (if positive)
- โขOverlap area = xOverlap * yOverlap (if both positive)
- โขTime: O(1), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
computeArea(-3, 0, 3, 4, 0, -1, 9, 2); Expected:
45 Test Case 2
Not run Input:
computeArea(-2, -2, 2, 2, -2, -2, 2, 2); Expected:
16 Test Case 3
Not run Input:
computeArea(0, 0, 0, 0, -1, -1, 1, 1); Expected:
4 ๐ Code Editor
๐ค Output