Set | Cleanest | Short | C++
Use set to keep intervals in sorted order.\n- Find the overlapping intervals and remove them.\n- Add the new intervals\n- Keep track of number of elements.\n\nc
- Use set to keep intervals in sorted order.\n- Find the overlapping intervals and remove them.\n- Add the new intervals\n- Keep track of number of elements.\n\n```c++\nclass CountIntervals {\n    set<pair<int, int>> st;\n    int cnt;\npublic:\n    CountIntervals() {\n        cnt = 0;\n    }\n    \n    void add(int left, int right) {\n        auto it = st.upper_bound({left, INT_MIN});\n        \n        if(it != st.begin() && (--it)->second < left) {\n            ++it;\n        }\n        \n        while(it != st.end() && it->first <= right) {\n            left = min(left, it->first);\n            right = max(right, it->second);\n            \n            cnt -= (it->second - it->first + 1);\n            it = st.erase(it);\n        }\n        \n        st.insert({ left, right });\n        cnt += (right - left + 1);\n    }\n    \n    int count() {\n        return cnt;\n    }\n};\n```
['C', 'Ordered Set']