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.

Analysis

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.

rectangle-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:
<pre><code> 
String foo = "bar";
</code></pre>
  • TiyaChu Max

    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.

  • Ameya Naik
  • w

    Hi,

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

  • Wang Sysc Sysc

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

  • Suzy

    Thank you for sharing! Very helpful.

  • Dawei

    Hi,

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

    Thanks,