C++ Simple Solution

  • 0
    class Solution {
        // This function calculates overlapping length of two given lines (if lines are overlapping)
        // Same function will be used for both horizontal and vertical lines.
        // For horizontal lines, line1 is left line (if not then we can swap two lines)
        // For vertical lines, line1 is lower line on plane (we'll swap if not. 
        int overlapping(pair<int, int> line1, pair<int, int> line2) {
            if (line2.first < line1.first) {
                std::swap(line1, line2);
            if (line2.first > line1.second) {
                return 0;
            int endCommon = std::min(line2.second, line1.second);
            return endCommon - line2.first;
        // Changed variable names to x and y to make them more clear
        int computeArea(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
            int areaOne = (x2 - x1) * (y2 - y1);
            int areaTwo = (x4 - x3) * (y4 - y3);
            int widthCommon = overlapping (pair<int, int>(x1, x2), pair<int, int>(x3, x4));
            int heightCommon = overlapping(pair<int, int>(y1, y2), pair<int, int>(y3, y4));
            auto areaCommon = heightCommon * widthCommon;
            return areaOne + areaTwo - areaCommon;

Log in to reply

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