Simple C++ Solution (Beats 81%) with Explanation
Code\n\nclass CountIntervals {\n    int count_val = 0;\n\n    // Stores disjoint intervals, ordered by their start\n    set<pair<int, int>> intervals{};\n\npubl
# Code\n```\nclass CountIntervals {\n    int count_val = 0;\n\n    // Stores disjoint intervals, ordered by their start\n    set<pair<int, int>> intervals{};\n\npublic:\n    /*\n        Goal of this function is to add in the interval [left, right] to intervals.\n        Note that we want to maintain that intervals stores only disjoint intervals.\n\n        So there are two types of intervals [l, r] in intervals \n        we need [left, right] to "merge" with:\n        1) left <= l <= right     Visual: [  { ]  } or [ { } ]\n        2) l < left <= r          Visual: { [ } ]\n\n        ^ In the visuals, [] represnts [left, right] and {} represents [l, r]\n\n        When we merge with an interval of type (1), we extend right to max(right, r)\n        When we merge with an interval of type (2), we extend left to l\n\n        We then remove [l, r], as once we add back in [left, right], the new [left, right]\n        will account for the integers in [l, r]\n\n        Simultaneously while doing this, we will update count_val \n        based on intervals we remove / add\n    */\n    void add(int left, int right) {\n\n        // Get the first of the case 1 intervals\n        auto iter = intervals.lower_bound({left, -1});\n\n        // Convert any case 2 interval into a case 1 interval by setting left to l\n        if (iter != intervals.begin()) {\n            auto prev = iter; prev--; // Only possible case 2 interval\n            if (left <= (*prev).second) {\n                left = (*prev).first;\n                iter = prev;\n            }\n        }\n\n        // Handle all case 1 intervals\n        while (iter != intervals.end() && (*iter).first <= right) {\n            auto [left_other, right_other] = *iter;\n\n            right = max(right, right_other);\n            count_val -= right_other - left_other + 1;\n\n            intervals.erase(iter++);\n        }\n\n        // Add in [left, right]\n        count_val += right - left + 1;\n        intervals.insert({left, right});\n    }\n    \n    int count() {\n        return count_val;\n    }\n};\n```
['C++']