Problem Description
You are given a list of intervals where each interval [start, end) represents a segment on a number line that must be painted on a specific day. The twist is that if an area has already been painted on a previous day, painting it again does not count as "new" work. For each day, determine the length of the segment that is painted for the first time.
Key Insights
- The problem requires merging intervals and computing the “gap” (or uncovered region) within the current interval that hasn’t been painted before.
- We can maintain a collection of already painted intervals (as merged disjoint segments). For each new interval, we only add the parts that are not covered by any existing intervals.
- Using an ordered data structure (balanced tree, sorted list, or ordered set) helps efficiently query and merge overlapping intervals.
- The challenge is merging intervals on the fly and keeping track of “new” painted segments without double counting.
Space and Time Complexity
Time Complexity: O(n log n) on average, since each insertion and search in the ordered interval set takes logarithmic time and merging is efficient due to non-overlapping intervals. Space Complexity: O(n), for storing the merged intervals.
Solution
We maintain a sorted list (or ordered set) of disjoint intervals that have already been painted. For each day's paint interval [L, R):
- Query the current collection to find all intervals that overlap with [L, R).
- Compute the length of the uncovered segments inside [L, R) by iterating over the overlapping intervals and summing gaps.
- Merge the overlapping intervals with the new paint interval to update the painted intervals.
- Record the new painted length. This ensures that overlapping areas are only counted once and that the data structure always reflects the union of all painted intervals so far.