KatInterview

Locate Uncovered Ranges Between Intervals

Greedy & IntervalsAuto-graded · 24 test cases
MediumAuto-gradedGreedy & Intervalsintervalssortingmerging

Last updated

Tests interval merging, sorting, and boundary logic to identify all missing integer ranges within the overall coverage span.

You are given a list of integer intervals intervals, where each interval is a pair [start, end] with both endpoints inclusive and start <= end.

Your task is to identify all uncovered ranges of integers that lie between the smallest and largest values covered by the union of all intervals.

Specifically:

  1. Merge all overlapping or adjacent intervals into a union of disjoint covered ranges.
  2. Let minCovered be the smallest integer in any interval, and maxCovered be the largest.
  3. Find every maximal contiguous range of integers in [minCovered, maxCovered] that is not covered by any interval.

Return these uncovered ranges as a list of disjoint intervals [gapStart, gapEnd] (inclusive), sorted in ascending order by gapStart.

Important: Two intervals like [1, 3] and [4, 6] are considered adjacent (they share no gap) because there is no integer strictly between 3 and 4.

Constraints

  • 1 <= len(intervals) <= 200000
  • Each interval endpoint is a 32-bit signed integer.
  • intervals[i][0] <= intervals[i][1] for all i.

Examples

Example 1

Input: locate_uncovered_ranges([[1, 3], [7, 10], [2, 4]])

Output: [[5, 6]]

Example 2

Input: locate_uncovered_ranges([[1, 2], [3, 5]])

Output: []

Example 3

Input: locate_uncovered_ranges([[10, 12], [1, 3], [6, 8]])

Output: [[4, 5], [9, 9]]

Hints

Hint 1

Sort the intervals by their starting points to process them in order from left to right.

Hint 2

Track the rightmost covered endpoint as you sweep through the sorted intervals; a gap exists when the next interval starts more than one unit away.

Hint 3

Remember that endpoints are inclusive integers—intervals [a, b] and [b+1, c] touch with no gap between them.