Find Maximal Uncovered Ranges - Problem

You are given an integer n which is the length of a 0-indexed array nums, and a 0-indexed 2D-array ranges, which is a list of sub-ranges of nums (sub-ranges may overlap).

Each row ranges[i] has exactly 2 cells:

  • ranges[i][0], which shows the start of the ith range (inclusive)
  • ranges[i][1], which shows the end of the ith range (inclusive)

These ranges cover some cells of nums and leave some cells uncovered. Your task is to find all of the uncovered ranges with maximal length.

Return a 2D-array answer of the uncovered ranges, sorted by the starting point in ascending order.

By all of the uncovered ranges with maximal length, we mean satisfying two conditions:

  • Each uncovered cell should belong to exactly one sub-range
  • There should not exist two ranges (l1, r1) and (l2, r2) such that r1 + 1 = l2

Input & Output

Example 1 — Basic Case
$ Input: n = 8, ranges = [[0,2],[5,7]]
Output: [[3,4]]
💡 Note: Positions 0-2 are covered by [0,2], positions 5-7 are covered by [5,7]. Positions 3-4 are uncovered, forming one maximal range [3,4].
Example 2 — Multiple Gaps
$ Input: n = 10, ranges = [[2,3],[7,8]]
Output: [[0,1],[4,6],[9,9]]
💡 Note: Three uncovered ranges: [0,1] before first range, [4,6] between ranges, and [9,9] after last range.
Example 3 — Overlapping Ranges
$ Input: n = 6, ranges = [[1,3],[2,5]]
Output: [[0,0]]
💡 Note: Ranges [1,3] and [2,5] overlap and merge to [1,5]. Only position 0 is uncovered.

Constraints

  • 1 ≤ n ≤ 50
  • 0 ≤ ranges.length ≤ 50
  • ranges[i].length == 2
  • 0 ≤ ranges[i][0] ≤ ranges[i][1] < n

Visualization

Tap to expand
Find Maximal Uncovered Ranges INPUT Array of length n = 8 0 1 2 3 4 5 6 7 indices Covered Uncovered Given Ranges: ranges = [[0,2], [5,7]] [0,2] [5,7] Input Values: n = 8 ranges = [[0,2],[5,7]] ALGORITHM STEPS 1 Sort Ranges By start index ascending 2 Merge Overlapping Combine adjacent ranges 3 Find Gaps Identify uncovered regions 4 Build Result Return maximal uncovered Processing: Sorted: [[0,2], [5,7]] Merged: [[0,2], [5,7]] Gap: after 2, before 5 Uncovered: [3, 4] 0-2 3-4 5-7 FINAL RESULT Uncovered range found: 0 1 2 3 4 5 6 7 Uncovered Output: [[3, 4]] Status: OK 1 maximal uncovered range Complexity: Time: O(m log m) Space: O(m) Key Insight: Sort and merge overlapping ranges first, then scan gaps between consecutive merged ranges. The gap between range[i].end + 1 and range[i+1].start - 1 forms a maximal uncovered range. Also check boundaries: [0, first_range_start-1] and [last_range_end+1, n-1] if they exist. TutorialsPoint - Find Maximal Uncovered Ranges | Optimal Solution
Asked in
Google 25 Amazon 20 Microsoft 15
12.0K Views
Medium Frequency
~15 min Avg. Time
450 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