Simple Java answer with explanation

  • 0

    It is an analytical math question that will test how can you figure out the intersection area, if any. A couple of things that may come out if you pay attention to the given picture for rectangles r1 and r2:

    1. Find if there is an intersection: you can figure it out by check if the r2's lower line is below the upper line of r1, r2's left line is before right line of r1 and so on.
    2. If there is an intersection, the area may be calculated by figuring out the area of the intersection by analyzing the coordinates. The intersection will be the rightmost x of two and the top of the ys.
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
            int firstArea = (C-A)*(D-B);//simple area calculation
            int secondArea = (G-E)*(H-F);
            int intersect = 0;
            //check if rectangles intersect.
            if(G>=A&&E<=C&&F<=D &&H>=B) {
                int lower_left_X = A>E?A:E;
                int lower_left_Y = B>F?B:F;
                int higher_left_Y = D>H?H:D;
                int lower_right_X = C>G?G:C;
                int length = higher_left_Y-lower_left_Y;
                int width = lower_right_X-lower_left_X;
                intersect = length*width;
            return firstArea+secondArea-intersect;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.