Problem Description
Design a data structure that receives a stream of non-negative integers and maintains a summary of the numbers seen so far as a list of disjoint intervals. You must be able to add a number to the stream and report the current list of intervals, merging intervals when necessary.
Key Insights
- Keep intervals sorted by their start values to efficiently locate where a new number fits.
- Use binary search (or an ordered container) to quickly find the intervals adjacent to the inserted number.
- Carefully merge the new number with neighboring intervals if they are contiguous or overlapping.
- Maintaining a sorted structure minimizes the work needed during getIntervals calls.
Space and Time Complexity
Time Complexity:
- addNum: O(N) in the worst-case scenario when merging intervals (where N is the number of intervals), but typically much faster using binary search.
- getIntervals: O(1) if simply returning the maintained list.
Space Complexity: O(N) for storing the list of intervals.
Solution
The solution involves maintaining a sorted list (or a balanced tree set) of intervals. When a new number is added:
- Use binary search to locate the position where the new number would fit.
- Check if the new number is already covered by an existing interval.
- Determine if it is adjacent to (or can extend) an interval on the left, on the right, or possibly both.
- Merge intervals if necessary. The process ensures that at any moment, the intervals list remains non-overlapping and sorted. This approach allows efficient updates as well as fast retrieval of the intervals.