Missing Ranges
The problem is asking to find the missing ranges in a sorted array. The range is given as [lower, upper]. We need to find all the ranges in which there are no numbers present from the array.
We can solve this problem by checking the gaps between successive numbers in the array. If the gap is more than 1, we know there are missing numbers.
Python solution:
|
|
We first add lower-1
and upper+1
to the list. This way, we can treat the start and end of the range in the same way as we treat the rest of the numbers in the list, and avoid special casing them.
We then iterate over the list. For each pair of consecutive numbers, we check if there are numbers missing between them by subtracting the first number from the second. If the difference is 2, then there’s exactly one missing number, which we add to the list of missing ranges as a range of itself. If the difference is more than 2, then there’s a range of missing numbers, and we add the range to the list of missing ranges.
Finally, we return the list of missing ranges.