Problem description:

You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in 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 smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

Example 1:

1
2
3
4
5
6
7
Input: nums = [0,1,3,50,75], lower = 0, upper = 99
Output: ["2","4->49","51->74","76->99"]
Explanation: The ranges are:
[2,2] --> "2"
[4,49] --> "4->49"
[51,74] --> "51->74"
[76,99] --> "76->99"

Solution:

  1. Find the range between lower and first element in the array.
  2. Find ranges between adjacent elements in the array.
  3. Find the range between upper and last element in the array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:
'''
1.

'''

if not nums:
return [self.formRange(lower, upper)]
res = []
if nums[0] > lower:
res.append(self.formRange(lower, nums[0]-1))

for i in range(len(nums)-1):
if nums[i+1] != nums[i] and nums[i+1] > nums[i] +1:
res.append(self.formRange(nums[i]+1, nums[i+1]-1))

if nums[-1] < upper:
res.append(self.formRange(nums[-1]+1, upper))
return res


def formRange(self, low, high):
if low == high:
return str(low)
else:
print(str(low)+ "->"+ str(high))
return str(low)+ "->"+ str(high)

time complexity: $O(n)$
space complexity: $O(1)$
reference:
related problem: