99.08% Beats || Simple Set based approach 💯✅
\n\n\n# Approach\n Describe your approach to solving the problem. \nFirst we initialise a set of pairs that stores the non intresecting intervals in the given i
![image.png](https://assets.leetcode.com/users/images/105e8d87-3d4c-40ee-b69b-9272468d1ae3_1728671025.7619207.png)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we initialise a set of pairs that stores the non intresecting intervals in the given intervals till now,\nthe element cur stores the number of elements in the range [0,1e9] which are present in atleast one interval,\nNow first we find the interval which has a possibility of intresection with the new interval to be inserted by using the lowerbound on the set and then we traverse the whole set and check for any possible intresection and merge it with the current interval and erase the existing interval from the set and update the cur according to that,\nand finally we check for any possibility of intresection of interval with the before interval then merge that also with the current interval if intresects and then \nfinally we will add the final current interval which has already mearged the possible intervals in the earlier intervals to the set and update the cur variable.\n\nfor every count function call we return the value in the cur variable.\n\n# Complexity\n- Time complexity:$$O(log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass CountIntervals {\npublic:\n    set<pair<int, int>> s;\n    int cur;\n    CountIntervals() {\n        s.clear();\n        cur = 0;\n    }\n\n    void add(int left, int right) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n        auto it = s.lower_bound({left, right});\n        while (it != s.end() and it->first <= right) {\n            left = min(it->first, left);\n            right = max(it->second, right);\n            cur -= (it->second - it->first + 1);\n            auto temp = it;\n            it++;\n            s.erase(temp);\n        }\n\n        if (it != s.begin()) {\n            it--;\n            if (it->second >= left) {\n                left = min(it->first, left);\n                right = max(it->second, right);\n                cur -= (it->second - it->first + 1);\n                auto temp = it;\n                it++;\n                s.erase(temp);\n            }\n        }\n\n        cur+=right-left+1;\n        s.insert({left,right});\n    }\n\n    int count() {\n        return cur;\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```
['Design', 'Ordered Set', 'C++']