✅✅Faster || Easy To Understand || C++ Code
Using Map\n\n Time Complexity :- O(logN) in best case and O(N) in worst case for add operation\n\n Space Complexity :- O(N)\n\n\nclass CountIntervals {\npublic:
* ***Using Map***\n\n* ***Time Complexity :- O(logN) in best case and O(N) in worst case for add operation***\n\n* ***Space Complexity :- O(N)***\n\n```\nclass CountIntervals {\npublic:\n    \n    map<int, int> mp;\n    \n    int total_count = 0;\n    \n    CountIntervals() {\n        \n    }\n    \n    void add(int left, int right) {\n        \n        // find the upper bound of left in map\n        \n        auto it = mp.upper_bound(left);\n        \n        // check if previous interval is overlapping with new_interval\n        \n        if(it != mp.begin() && left <= prev(it) -> second)\n        {\n            it = prev(it);\n        }\n        \n        // delete the overlapping intervals and update total_count\n        \n        while(it != mp.end() && it -> first <= right)\n        {\n            // update left \n            \n            left = min(left, it -> first);\n            \n            // update right\n            \n            right = max(right, it -> second);\n            \n            // update count\n            \n            total_count -= it -> second - it -> first + 1;\n            \n            // erase the current interval and update pointer\n            \n            it = mp.erase(it);\n        }\n        \n        // push into map\n        \n        mp[left] = right;\n        \n        // update total_count\n        \n        total_count += right - left + 1;\n    }\n    \n    int count() {\n        \n        return total_count;\n    }\n};\n\n/**\n * Your CountIntervals object will be instantiated and called as such:\n * CountIntervals* obj = new CountIntervals();\n * obj->add(left,right);\n * int param_2 = obj->count();\n */\n```
['C', 'C++']