Check if All the Integers in a Range Are Covered Problem
Description
LeetCode Problem 1893.
You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [start_i, end_i] represents an inclusive interval between start_i and end_i.
Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.
An integer x is covered by an interval ranges[i] = [start_i, end_i] if start_i <= x <= end_i.
Example 1:
Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5
Output: true
Explanation: Every integer between 2 and 5 is covered:
- 2 is covered by the first range.
- 3 and 4 are covered by the second range.
- 5 is covered by the third range.
Example 2:
Input: ranges = [[1,10],[10,20]], left = 21, right = 21
Output: false
Explanation: 21 is not covered by any range.
Constraints:
1 <= ranges.length <= 501 <= start_i <= end_i <= 501 <= left <= right <= 50
Solution
Approach: Difference Array
Use a difference array diff over the values 1 to 50. For each range [l, r], add 1 at diff[l] and subtract 1 at diff[r + 1].
Then sweep the values in order, keeping a running prefix sum s: it is the number of ranges covering the current value. If s is 0 for some value between left and right, that integer is not covered, so return false. If the sweep finishes without that happening, return true.
Complexity: O(n + M) time and O(M) space, where n is the number of ranges and M = 50 is the largest value.
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
diff = [0] * 52
for l, r in ranges:
diff[l] += 1
diff[r + 1] -= 1
s = 0
for i, x in enumerate(diff):
s += x
if s <= 0 and left <= i <= right:
return False
return True