Problem Description
We are asked to design a data structure (CountIntervals) that starts with an empty set of intervals and supports two operations:
- add(left, right): Insert an interval [left, right] into the set.
- count(): Return the number of unique integers present across all intervals. Note that intervals may overlap, and overlapping intervals must be merged so that each integer is only counted once.
Key Insights
- We can store the intervals in a sorted data structure ensuring the intervals are non-overlapping (merged).
- On each add operation, we have to merge any intervals that overlap with the new interval.
- Maintaining a running sum (or recomputing the total after each merge) allows the count operation to run in O(1) time.
- Techniques include binary search (or an ordered set / TreeMap) to efficiently find overlapping intervals.
Space and Time Complexity
Time Complexity:
- Adding an interval takes O(m + log n) time where m is the number of intervals merged and n is the number of disjoint intervals stored.
- Getting the count takes O(1) time. Space Complexity: O(n) where n is the number of disjoint intervals maintained in the data structure.
Solution
We maintain a sorted list (or tree-based structure) of disjoint intervals and a variable to keep track of the total count of integers currently covered. When adding a new interval [left, right]:
- Find all intervals in the structure that overlap with [left, right].
- Remove these intervals and merge them with the new interval (update left = min(existing.left, left) and right = max(existing.right, right)).
- Subtract the count of removed intervals from the total count.
- Insert the merged interval and update the total count accordingly. This ensures that there are no overlaps in the maintained intervals and that the count is always correct.
The following implementations in Python, JavaScript, C++, and Java illustrate the approach with detailed comments.