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.
Return true if each integer in the inclusive interval [left, right] is covered by at least one interval in ranges. Return false otherwise.
ranges be sorted or unordered?
ranges distinct or can they overlap?
ranges and the range for left and right?
Our goal is to check if every integer from left to right is included in at least one of the intervals in ranges. Here is a step-by-step strategy:
covered initialized to False with a size covering from left to right.ranges and mark the corresponding elements in covered as True.covered list corresponding to the range [left, right] are True.We can initialize a boolean array representing the coverage status of each number in the range [left, right]. For each range in ranges, mark the appropriate indices as covered. Finally, validate that all indices corresponding to [left, right] are True.
def isCovered(ranges, left, right):
# Create a list to keep track of which numbers from left to right are covered.
covered = [False] * (right - left + 1)
# Mark the numbers covered by the ranges
for start, end in ranges:
for num in range(max(start, left), min(end, right) + 1):
covered[num - left] = True
# Check if all numbers from left to right are covered
return all(covered)
# Example usage:
ranges = [[1,2], [3,4], [5,6]]
left = 2
right = 5
print(isCovered(ranges, left, right)) # Output: True
covered List:
covered list is the size of the interval [left, right], hence it has (right - left + 1) elements.[start, end], we iterate only over the intersection with [left, right].max(start, left) ensures we don’t start before left.min(end, right) ensures we don’t go past right.covered[num - left] as True where num is within the intersection.all(covered) function checks if all elements in the covered list are True.N is the number of intervals in ranges and R is the average size of the intersection between [start, end] and [left, right].R is the length of the interval [left, right].This solution should be efficient enough given typical problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?