Balance BST using Python SortedList
Code\n\nimport sortedcontainers\n\nclass CountIntervals(object):\n\n    def __init__(self):\n        # space O(n)\n        self.intervals = sortedcontainers.Sor
# Code\n```\nimport sortedcontainers\n\nclass CountIntervals(object):\n\n    def __init__(self):\n        # space O(n)\n        self.intervals = sortedcontainers.SortedList()\n        self.total_num = 0\n\n    # time O(n^2.log(n)) worst case, O(n.log(n)) average\n    def add(self, left, right):\n        """\n        :type left: int\n        :type right: int\n        :rtype: None\n        """\n\n        i = self.intervals.bisect_left([left, 0])\n        if i-1 >= 0:\n            prev_end = self.intervals[i-1][1]\n            if right <= prev_end:\n                return\n            if left <= prev_end:\n                left = prev_end + 1\n            if left > right:\n                return\n        \n        to_add = []\n        for start, end in self.intervals.irange([left, 0], [right, 10**9]):  # time O(k+log(n))\n            if right < start:\n                break\n            if left <= start-1:\n                to_add.append([left, start-1])\n            left = end+1\n        if left <= right:\n            to_add.append([left, right])\n        \n        for start, end in to_add:\n            self.total_num += end-start+1\n            self.intervals.add([start, end])  # time O(k.log(n))\n\n    # time O(1)\n    def count(self):\n        """\n        :rtype: int\n        """\n        \n        return self.total_num\n```
['Python']