Missing Ranges Problem
Description
LeetCode Problem 163.
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are within the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the shortest sorted list of ranges that exactly covers all the missing numbers. That is, no element of nums is included in any of the ranges, and each missing number is covered by one of the ranges.
Example 1:
Input: nums = [0,1,3,50,75], lower = 0, upper = 99
Output: [[2,2],[4,49],[51,74],[76,99]]
Explanation: The ranges are:
[2,2]
[4,49]
[51,74]
[76,99]
Example 2:
Input: nums = [-1], lower = -1, upper = -1
Output: []
Explanation: There are no missing ranges since there are no missing numbers.
Constraints:
-10^9 <= lower <= upper <= 10^90 <= nums.length <= 100lower <= nums[i] <= upper- All the values of
numsare unique.
Solution
Approach: Scan the Gaps
Since nums is sorted and has no duplicates, the missing numbers are exactly the gaps between neighbors. Two neighbors a < b leave a gap when b - a > 1, and the missing range is [a + 1, b - 1].
The gaps at the two ends need the same treatment, and we can handle them without special cases by imagining two extra numbers: lower - 1 before the array and upper + 1 after it. Walk through nums followed by upper + 1, keep the previous number prev (starting at lower - 1), and add [prev + 1, x - 1] whenever x - prev > 1.
This also handles an empty nums: the only pair is lower - 1 and upper + 1, which gives the single range [lower, upper].
In Java and C++ the virtual numbers are kept in 64-bit variables, so lower - 1 and upper + 1 can never overflow, even if lower or upper sat at the edge of the int range.
Complexity: O(n) time, where n is the length of nums. O(1) extra space besides the output.
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[List[int]]:
ans = []
prev = lower - 1 # the last number known to be present (a virtual one before lower)
for x in nums + [upper + 1]: # a virtual number after upper closes the last gap
if x - prev > 1:
ans.append([prev + 1, x - 1])
prev = x
return ans