Imagine you're a booking system manager for a popular venue. You need to keep track of time slots that are reserved and quickly answer: "How many time units are currently booked?"
Your task is to implement a CountIntervals data structure that efficiently manages overlapping intervals and counts unique integers across all intervals.
The Challenge:
add(left, right)- Reserve a new time interval [left, right] (inclusive)count()- Return total unique time units that are reserved
Key Insight: When intervals overlap, they should be merged automatically to avoid double-counting. For example, intervals [1,3] and [2,5] should be treated as [1,5] containing 5 unique integers.
Example: Adding [2,3] and [4,5] gives count=4, then adding [6,7] gives count=6. But if we add [5,6], it merges [4,5] and [6,7] into [4,7], keeping count=6.
Input & Output
Visualization
Time & Space Complexity
Each count() call requires sorting n intervals and merging them
Store all n intervals in memory
Constraints
- 1 โค left โค right โค 109
- At most 105 calls to add and count
- Important: Intervals are inclusive on both ends
- The total count will never exceed 2 ร 108