TreeMap || O(n.logn) || Simple
\n\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(n.logn)\n- Space complexity:\n Add your space complexity here, e.g. O(n) \nO
![image.png](https://assets.leetcode.com/users/images/1a6e7441-0cf0-49f2-9104-85be3ac518d5_1727502119.5216935.png)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n.logn)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```java []\nclass CountIntervals {\n    TreeMap<Integer, Integer> mh = new TreeMap<>();\n    static int count = 0;\n\n    public CountIntervals() {\n        count = 0;\n    }\n\n    public void add(int s, int e) {\n        Integer end = mh.ceilingKey(s);\n        if (end == null || (end > e && mh.get(end) > e)) {\n            mh.put(e, s);\n            count += e - s + 1;\n            return;\n        }\n        while (true) {\n            end = mh.ceilingKey(s);\n            if (end == null) {\n                mh.put(e, s);\n                count += e - s + 1;\n                return;\n            }\n            if (end >= s && end <= e) {\n                Integer start = mh.get(end);\n                if (s > start) s = start;\n                count -= (end - start + 1);\n                mh.remove(end);\n            } else if (end > e) {\n                Integer start = mh.get(end);\n                if (start >= s && start <= e) {\n                    e = end;\n                    count -= (end - start + 1);\n                    mh.remove(end);\n                } else if (start > e) {\n                    mh.put(e, s);\n                    count += e - s + 1;\n                    return;\n                } else {\n                    return;\n                }\n            }\n        }\n    }\n\n    public int count() {\n        return count;\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', 'Java']