Skip to content

223. Rectangle Area

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  int computeArea(long A, long B, long C, long D,  //
                  long E, long F, long G, long H) {
    const long x = max(A, E) < min(C, G) ? (min(C, G) - max(A, E)) : 0;
    const long y = max(B, F) < min(D, H) ? (min(D, H) - max(B, F)) : 0;
    return (C - A) * (D - B) + (G - E) * (H - F) - x * y;
  }
};
1
2
3
4
5
6
7
class Solution {
  public int computeArea(long A, long B, long C, long D, long E, long F, long G, long H) {
    final long x = Math.max(A, E) < Math.min(C, G) ? (Math.min(C, G) - Math.max(A, E)) : 0;
    final long y = Math.max(B, F) < Math.min(D, H) ? (Math.min(D, H) - Math.max(B, F)) : 0;
    return (int) ((C - A) * (D - B) + (G - E) * (H - F) - x * y);
  }
}
1
2
3
4
5
6
7
class Solution:
  def computeArea(self,
                  A: int, B: int, C: int, D: int,
                  E: int, F: int, G: int, H: int) -> int:
    x = min(C, G) - max(A, E) if max(A, E) < min(C, G) else 0
    y = min(D, H) - max(B, F) if max(B, F) < min(D, H) else 0
    return (C - A) * (D - B) + (G - E) * (H - F) - x * y