Simple Solution with *Meaningful* Variable Names - least number of lines usually doesn't mean the best solution


  • 0
    R

    I keep seeing solutions where people collapse as many instructions as possible into a single line, thinking that it looks more elegant. It doesn't. Writing an expression on the whiteboard like below during an interview will definitely make you lose points even if it's correct:

    C < E ? 0 : C < G ? A < E ? C-E : C-A : A > G ? 0 : A < E ? G-E : G-A;

    Your code ALWAYS needs to be understandable even at the cost of making the code and variable names longer.
    Here's my solution which I think is understandable enough, but still short and simple.

    public class Solution {
        public int ComputeArea(int A, int B, int C, int D, int E, int F, int G, int H) 
        {
            bool isFirstRectLeft = A <= E;
    
            int xLeftRectTopRight = isFirstRectLeft ? C : G;
            int xRightRectTopRight = isFirstRectLeft ? G : C;
            int xRightRectBottomLeft = isFirstRectLeft ? E : A;
    
            int xEdgeIntersection = 
                Math.Min(xLeftRectTopRight, xRightRectTopRight) - Math.Min(xLeftRectTopRight, xRightRectBottomLeft);
    
            bool isFirstRectBottom = B <= F;
    
            int xBottomRectTopRight = isFirstRectBottom ? D : H;
            int xTopRectTopRight = isFirstRectBottom ? H : D;
            int xTopRectBottomLeft = isFirstRectBottom ? F : B;
    
            int yEdgeIntersection = 
                Math.Min(xBottomRectTopRight, xTopRectTopRight) - Math.Min(xBottomRectTopRight, xTopRectBottomLeft);
    
            int areaRec1 = Math.Abs((A - C) * (B - D));
            int areaRec2 = Math.Abs((E - G) * (F - H));
            int areaIntersection = xEdgeIntersection * yEdgeIntersection;
    
            return areaRec1 + areaRec2 - areaIntersection;    
        }
    }
    

Log in to reply
 

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