Set+Binary Search
For detailed explanation on a more generic problem check: Range Module Solution\n\n# Code\n\nclass CountIntervals {\npublic:\n    set<pair<int,int>> st;\n    in
For detailed explanation on a more generic problem check: [Range Module Solution](https://leetcode.com/problems/range-module/solutions/5313893/set-binary-search/)\n\n# Code\n```\nclass CountIntervals {\npublic:\n    set<pair<int,int>> st;\n    int cnt;\n    CountIntervals() {\n        ios::sync_with_stdio(0);\n        cin.tie(0); cout.tie(0);\n        cnt=0;\n    }\n    \n    void add(int left, int right) {\n        right++;\n        auto itr = st.upper_bound({left, INT_MIN});\n        if(itr!=st.begin() && (--itr)->second <left)++itr;\n        for(;itr!=st.end() && itr->first<=right;st.erase(itr++))\n        {\n            left = min(left, itr->first);\n            right = max(right, itr->second);\n            cnt-=(itr->second-itr->first);\n        }\n        st.insert({left,right});\n        cnt+=right-left;\n    }\n    \n    int count() {\n        return cnt;\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```
['Binary Search', 'Ordered Set', 'C++']