Problem Description
Given a 0-indexed array of length n and a list of possibly overlapping ranges that indicate covered portions of the array, the objective is to find all the maximal uncovered ranges. An uncovered range must satisfy:
- Every uncovered cell belongs to exactly one sub-range.
- There are no two sub-ranges that are adjacent (i.e. no two ranges where the end of one plus one equals the start of the next).
In short, you need to return a sorted list of intervals (by starting index ascending) that represent contiguous uncovered segments in the array.
Key Insights
- Instead of processing the entire array (n can be up to 10^9), merge the given covered ranges.
- Merge overlapping or contiguous covered intervals to compute disjoint intervals of coverage.
- The uncovered intervals are the gaps between these merged covered intervals as well as possible gaps at the beginning and end of the array.
- Sorting the ranges first (by start index) allows efficient merging.
Space and Time Complexity
Time Complexity: O(m log m) where m is the number of ranges (up to 10^6) due to sorting. Space Complexity: O(m) for storing the merged coverage intervals.
Solution
The solution consists of the following steps:
- If the ranges list is empty, the whole array [0, n-1] is uncovered.
- Sort the ranges based on the starting index.
- Merge overlapping or contiguous ranges to form a list of disjoint covered intervals.
- Find the gaps (uncovered ranges) between these merged intervals.
- Return the uncovered ranges ensuring each uncovered cell belongs to one maximal contiguous sub-range (thus no two uncovered intervals will have r1+1 = l2).