C++, O(n*log(n))
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass CountIntervals {\n    int lim = 1e9 + 50;\n    set<pair<int,int> >s;\n    int ans = 0;\npublic:\n    CountIntervals() {\n        s.insert({1,lim});\n    }\n    \n    void add(int left, int right) {\n        auto it = s.lower_bound({left,0});\n        if(it != s.begin()) it--;\n        vector<pair<int,int> >adds,kills;\n        while(it != s.end()){\n            int L = (*it).first;\n            int R = (*it).second;\n            if(L > right) break;\n            it++;\n            if(R < left) continue;\n            kills.push_back({L,R});\n            if(L >= left && R <= right){\n                ans+=(R-L+1);\n                continue;\n            }\n            if(L < left){\n                ans+=(min(right,R) - left +1);\n                adds.push_back({L,left-1});\n                if(R > right){\n                    adds.push_back({right+1,R});\n                }\n                continue;\n            }\n            if(L>= left && R > right){\n                ans+=(right - L + 1);\n                adds.push_back({right+1,R});\n            }\n        }\n        for(auto x: kills){\n            s.erase({x.first,x.second});\n        }\n        for(auto x:adds){\n            s.insert({x.first,x.second});\n        }\n    }\n    \n    int count() {\n        return ans;\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++']