Find Maximal Uncovered Ranges - Problem
๐ฏ Find Maximal Uncovered Ranges
Imagine you have a bookshelf with n positions (indexed 0 to n-1), and you're given a list of ranges that represent which sections are already occupied by books. Your task is to find all the empty sections on the shelf, but with a twist - you want to group adjacent empty positions into the largest possible continuous ranges.
Given:
n- the total length of the array (bookshelf)ranges- a 2D array where eachranges[i] = [start, end]represents a covered section (inclusive)
Goal: Return all uncovered ranges in their maximal form, sorted by starting position.
Key Rules:
- Each uncovered position should belong to exactly one range
- Adjacent ranges should be merged (e.g., [1,2] and [3,4] become [1,4])
- Ranges may overlap in the input - handle this correctly!
Example: If n=5 and ranges=[[0,1], [3,3]], then positions 0,1,3 are covered, leaving positions 2 and 4 uncovered. The result is [[2,2], [4,4]].
Input & Output
example_1.py โ Basic Case
$
Input:
n = 5, ranges = [[0, 1], [3, 3]]
โบ
Output:
[[2, 2], [4, 4]]
๐ก Note:
Positions 0, 1, and 3 are covered. Positions 2 and 4 are uncovered, each forming their own maximal range.
example_2.py โ Overlapping Ranges
$
Input:
n = 8, ranges = [[1, 3], [2, 5], [7, 7]]
โบ
Output:
[[0, 0], [6, 6]]
๐ก Note:
Ranges [1,3] and [2,5] overlap and merge to cover [1,5]. Position 7 is also covered. Uncovered positions are 0 and 6.
example_3.py โ Edge Case - No Ranges
$
Input:
n = 3, ranges = []
โบ
Output:
[[0, 2]]
๐ก Note:
No positions are covered, so the entire array [0, 2] is one maximal uncovered range.
Constraints
- 1 โค n โค 104
- 0 โค ranges.length โค 100
- ranges[i].length == 2
- 0 โค ranges[i][0] โค ranges[i][1] < n
- Ranges may overlap or be adjacent
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
The shelf has scattered book sections covering various ranges
2
Sort Sections
Arrange book sections in order from left to right
3
Merge Adjacent
Combine overlapping or touching book sections
4
Find Gaps
Identify all empty spaces between organized book sections
Key Takeaway
๐ฏ Key Insight: By first merging overlapping ranges, we transform a complex coverage problem into a simple gap-finding problem between sorted intervals.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code