Union of Intervals
every time when add method is called we are adding it in the set and checking if the prev interval\'s right is greater than left of current interval if its grea
every time when add method is called we are adding it in the set and checking if the prev interval\'s right is greater than left of current interval if its greater than we are merging them same we are doing for the next element\'s starting is lesser than cur than we are merging curent element with that interval \n\nsuppose our set is like {1,2}, {4,5}\nwhen we add {1,3 } in the set  {1,2}, {1,3},{4,5}\nthen we will remove {1,2} and {1,3 } and insert {1,3} then our set will be like {1,3} , {4,5} same can be dont for greater element \nalso in count method we need to have count in o(1) else it will give tle if traverse set again and again \nwe can keep track of count using a global variable \n```\n#define mp make_pair\n#define ff first\n#define pii pair<int,int>\n#define ss second\nset<pair<int,int>> s;\nint cnt=0;\nclass CountIntervals {\npublic:\n    \n    CountIntervals() {\n        s.clear();\n\t\tcnt=0;\n    }\n    \n    void add(int l, int r) {\n\t\tauto iz = s.find(mp(l,r));\n\t\tif(iz!=s.end())return;\n        s.insert(mp(l,r));\n\t\tcnt+=(r-l+1);\n        auto it = s.find(mp(l,r));\n\t\tfor(int i = 0 ;i<2;i++)\n\t\t{\n\n        int flag=0;\n        pii to_insert;\n        if(it!=s.begin())\n        {\n            auto pr = prev(it);\n            if(pr->ss>=it->ff)\n            {\n            flag=1;\n                 to_insert=(mp(min(pr->ff,it->ff),max(it->ss,pr->ss)));\n\t\t\t\tcnt-=(pr->ss-pr->ff+1);\n\t\t\t\tcnt-=(it->ss-it->ff+1);\n\t\t\t\tcnt+=(to_insert.ss-to_insert.ff+1);\n                s.erase(pr);\n                s.erase(it);\n                s.insert(to_insert);\n\t\t\t\tit = s.find(to_insert);\n            }\n        }\n      \n        if(it!=prev(s.end()))\n        {\n            auto nx = next(it);\n            if(it->ss>=nx->ff)\n            {\n                to_insert=(mp(min(it->ff,nx->ff),max(nx->ss,it->ss)));\t\t\t\n\t\t\t\tcnt-=(nx->ss-nx->ff+1);\n\t\t\t\tcnt-=(it->ss-it->ff)+1;\n\t\t\t\tcnt+=(to_insert.ss-to_insert.ff+1);\n                s.erase(nx);\n                s.erase(it);\n                s.insert(to_insert);\n\t\t\t\tit=s.find(to_insert);\n            }\n        }\n\t\t}\n\t\treturn;\n    }\n    \n    int count() {\n        return cnt;\n    }\n};\n```
['Union Find', 'C', 'Ordered Set']