Find All Numbers Disappeared in an Array II Problem
Description
LeetCode Problem 4031.
You are given an integer array nums and two integers lower and upper.
A missing integer is an integer in the inclusive range [lower, upper] that does not appear in nums.
Return a 2D integer array where each element is of the form [start, end], representing a contiguous range of missing integers. Return the ranges in increasing order. If there are no missing integers, return an empty array.
Note: Consecutive missing integers should be grouped into a single range.
Example 1:
Input: nums = [3,9,7], lower = 1, upper = 12
Output: [[1,2],[4,6],[8,8],[10,12]]
Explanation:
- The missing integers are [1, 2, 4, 5, 6, 8, 10, 11, 12].
- Grouping the missing integers into the minimum number of contiguous ranges, we get [1, 2], [4, 6], [8, 8], and [10, 12].
- Therefore, the answer is [[1, 2], [4, 6], [8, 8], [10, 12]].
Example 2:
Input: nums = [1,1], lower = 5, upper = 7
Output: [[5,7]]
Explanation:
- The missing integers are [5, 6, 7].
- Grouping the missing integers into the minimum number of contiguous ranges, we get [5, 7].
- Therefore, the answer is [[5, 7]].
Example 3:
Input: nums = [2,3,5], lower = 2, upper = 3
Output: []
Explanation:
- There are no missing integers.
- Therefore, the answer is [].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^51 <= lower <= upper <= 10^5
Solution
Approach: Sorting
Sort nums and scan it, keeping prev, the last present number inside [lower, upper] (initially lower - 1).
Skip values outside [lower, upper]. For a value x with x - prev > 1, the numbers prev + 1 .. x - 1 are missing, so add that range and set prev = x. After the scan, if prev < upper, the tail [prev + 1, upper] is missing too.
Complexity: time O(n log n), space O(log n) besides the output, where n = nums.length.
class Solution:
def findDisappearedNumbers(
self, nums: List[int], lower: int, upper: int
) -> List[List[int]]:
ans = []
prev = lower - 1
for x in sorted(set(nums)):
if x < lower:
continue
if x > upper:
break
if x - prev > 1:
ans.append([prev + 1, x - 1])
prev = x
if prev < upper:
ans.append([prev + 1, upper])
return ans