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 each ranges[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
๐Ÿ“š Library Shelf OrganizationStep 1: Initial scattered book sectionsBooksBooksBooksBooksStep 2: Sort sections by positionBooksBooksBooksBooksStep 3: Merge overlapping/adjacent sectionsMerged BooksMerged BooksStep 4: Identify empty gaps (uncovered ranges)GapBooksGapBooksGapGreen sections represent the maximal uncovered ranges we want to find!
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.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen