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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit