Identify Gaps in a Sorted Array Within Bounds
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests interval reasoning, array traversal, edge case handling with boundaries, and formatting output for missing number ranges.
You are given a sorted array nums containing distinct integers, along with two integers lower and upper that define an inclusive range [lower, upper].
Your task is to identify all contiguous sequences of integers within [lower, upper] that do not appear in nums, and return them as formatted strings.
Important Rules:
- Only consider the interval
[lower, upper](both endpoints inclusive) - Ignore any elements in
numsthat fall outside[lower, upper] - A number is "missing" if it lies within
[lower, upper]and does not appear innums - Group consecutive missing numbers into ranges
Output Format:
- For a single missing number, return it as a string:
"5" - For a contiguous sequence of two or more missing numbers, use range notation:
"5->10"(meaning 5, 6, 7, 8, 9, 10 are all missing) - Return all missing ranges in ascending order
Constraints:
0 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 1numsis sorted in strictly increasing order (all elements are unique)-2^31 <= lower <= upper <= 2^31 - 1
Examples
Example 1
Input: identify_missing_ranges([0, 1, 3, 50, 75], 0, 99)
Output: ['2', '4->49', '51->74', '76->99']
Example 2
Input: identify_missing_ranges([0, 1, 2, 3, 4], 0, 4)
Output: []
Example 3
Input: identify_missing_ranges([], 1, 1)
Output: ['1']
Example 4
Input: identify_missing_ranges([2, 4, 6], 1, 7)
Output: ['1', '3', '5', '7']
Hints
Hint 1
Use a sentinel value just before the interval starts (lower - 1) to handle the leading edge uniformly with gaps between array elements.
Hint 2
Process each number in the array and check if there's a gap between it and the last covered position. Skip elements outside [lower, upper] entirely.
Hint 3
After processing all array elements, check if there's a trailing gap between the last covered position and the upper bound.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core strategy is to maintain a tracker for the last position we've accounted for within the target interval, then identify gaps as we scan through the sorted array.
Algorithm:
-
Initialize
last_coveredtolower - 1. This sentinel value sits just before the interval, allowing us to treat the leading edge uniformly with internal gaps. -
Iterate through each number in the input array:
- Skip numbers strictly less than
lower(they're outside our range of interest) - Stop processing when we encounter a number strictly greater than
upper(the sorted property guarantees all subsequent numbers are also outside) - For numbers within
[lower, upper], check if there's a gap betweenlast_coveredand this number - If
num > last_covered + 1, we've found a missing range fromlast_covered + 1tonum - 1—emit it - Update
last_coveredto the current number
- Skip numbers strictly less than
-
After processing all array elements, check for a trailing gap: if
last_covered < upper, emit the range fromlast_covered + 1toupper. -
Use a helper function to format ranges: single numbers as
"n"and multi-number ranges as"start->end".
Why This Works:
The algorithm maintains an invariant: after processing each in-range element, all missing numbers in [lower, last_covered] have been identified and emitted as maximal contiguous ranges. Since the input is sorted and contains distinct values, any gap between consecutive processed numbers represents exactly the missing values in that span. The sentinel initialization handles the leading edge cleanly, and the final check handles the trailing edge.
Complexity:
- Time: O(n) where n is the length of the input array. We make a single pass through the array, and each range formatting operation takes constant time plus output size.
- Space: O(1) auxiliary space beyond the output list. We only maintain a constant number of variables (
last_coveredand loop state).
from typing import List
def identify_missing_ranges(nums: List[int], lower: int, upper: int) -> List[str]:
result = []
last_covered = lower - 1
def format_range(start: int, end: int) -> None:
if start == end:
result.append(str(start))
else:
result.append(f"{start}->{end}")
for num in nums:
if num < lower:
continue
if num > upper:
break
if num > last_covered + 1:
format_range(last_covered + 1, num - 1)
last_covered = num
if last_covered < upper:
format_range(last_covered + 1, upper)
return result