LeetCode – Rectangle Area (Java)

Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner coordinates.


This problem can be converted as a overlap internal problem. On the x-axis, there are (A,C) and (E,G); on the y-axis, there are (F,H) and (B,D). If they do not have overlap, the total area is the sum of 2 rectangle areas. If they have overlap, the total area should minus the overlap area.


Java Solution

public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    if(C<E||G<A )
        return (G-E)*(H-F) + (C-A)*(D-B);
    if(D<F || H<B)
        return (G-E)*(H-F) + (C-A)*(D-B);
    int right = Math.min(C,G);
    int left = Math.max(A,E);
    int top = Math.min(H,D);
    int bottom = Math.max(F,B);
    return (G-E)*(H-F) + (C-A)*(D-B) - (right-left)*(top-bottom);
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Dawei on 2015-6-28


    There is a mistake in your code. When right-left or top-bottom is negetive, there is no overlap.


  2. Suzy on 2015-7-16

    Thank you for sharing! Very helpful.

  3. Wang Sysc Sysc on 2015-10-11

    I think no way you can make right-left negative/ top-bottom negative.

  4. w on 2016-4-30


    I have a question. Why you can assume C always bigger than A?

  5. Ameya Naik on 2016-5-20
  6. TiyaChu Max on 2016-8-16

    With your interval logic, we can perhaps reduce the conditions:

    typedef pair INTERVAL;

    long intersect(INTERVAL a, INTERVAL b){
    return min(a.second, b.second) - max(a.first, b.first);

    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    long x = intersect(INTERVAL(A,C), INTERVAL(E, G));
    long y = intersect(INTERVAL(B,D), INTERVAL(F,H));

    long area = (long)(C - A) * ( D - B) + (long) (G -E) * (H -F);

    if (x < 0 || y < 0 ) return area;
    else return area - x * y;

    // The idea being that a negative intersection in either direction, x or y implies that the two rectangles don’t intersect. ‘long’s are used instead of ‘int’s because leetcode says that the output never exceeds INT_MAX, but our computations may.

Leave a comment