Track Covered Spans Under Add, Erase and Check Commands
Data Structure DesignAuto-graded · 18 test casesLast updated
Maintain a set of half-open real intervals under add, remove and fully-covered queries, merging touching spans and splitting spans on removal.
You are given a sequence of commands to run, in order, against an initially empty collection of covered stretches of the number line. Every stretch is a half-open interval [left, right): it includes left and excludes right, and it contains every real number in between, not only integers.
Each command is one of three kinds:
"addRange"with arguments[left, right]: mark every real number in[left, right)as covered. Covered stretches that overlap or touch the new one become one continuous stretch. For example, covering[1, 5)and then[5, 10)leaves[1, 10)covered."removeRange"with arguments[left, right]: mark every real number in[left, right)as no longer covered. This can split a stretch in two. Removing[5, 8)from[1, 10)leaves[1, 5)and[8, 10). Removing from an area that is not covered changes nothing."queryRange"with arguments[left, right]: report whether every real number in[left, right)is currently covered. This command does not change the collection.
Implement a function that takes the list of command names and the parallel list of argument pairs, runs the commands in order, and returns a list of results with one entry per command:
- for
"addRange"and"removeRange", the entry isNone; - for
"queryRange", the entry isTrueorFalse.
A query on an empty collection returns False.
Constraints
operationsandargumentshave the same length, between 1 and 20,000.- Each operation name is exactly
"addRange","removeRange"or"queryRange". - Each element of
argumentsis a pair[left, right]with0 <= left < right <= 10^9. - The collection starts empty.
Examples
Example 1
Input: track_covered_spans(['addRange', 'removeRange', 'queryRange', 'queryRange', 'queryRange'], [[10, 20], [14, 16], [10, 14], [13, 15], [16, 17]])
Output: [None, None, True, False, True]
Example 2
Input: track_covered_spans(['addRange', 'addRange', 'queryRange', 'removeRange', 'queryRange', 'queryRange'], [[1, 5], [5, 10], [1, 10], [3, 7], [1, 3], [7, 10]])
Output: [None, None, True, None, True, True]
Example 3
Input: track_covered_spans(['queryRange', 'addRange', 'queryRange', 'removeRange', 'queryRange'], [[0, 100], [0, 100], [0, 100], [20, 80], [10, 20]])
Output: [False, None, True, None, True]
Hints
Hint 1
Keep the covered area as a sorted list of disjoint stretches, so each command only needs to look at the stretches near its endpoints. Keep a parallel list of start values so you can binary search.
Hint 2
Because touching stretches must merge, a stretch ending exactly at the new left end, or starting exactly at the new right end, must be absorbed when adding. Scan forward from the first stretch that could touch the new one while its start is at most the new right end, and widen the new stretch as you go.
Hint 3
For removal, find the first stretch that might reach past `left`, then walk over every stretch starting before `right`. Each of those leaves at most a left remainder `[a, left)` and a right remainder `[right, b)`. For a query, only the single stretch whose start is the largest one not exceeding `left` can possibly cover the range.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the covered area as a list of disjoint, non-touching stretches [start, end) sorted by start, together with a parallel list starts of just the start values so that bisect can be used.
- addRange(l, r):
- Use
bisect_left(starts, l)to find the first stretch starting at or afterl. - Step back by one if the previous stretch ends at or after
l. It overlaps or touches the new range. - Walk forward while the next stretch starts at or before the (growing) right end. Fold each one in by taking the minimum start and maximum end.
- Replace all the visited stretches with the single merged stretch.
- Use
- removeRange(l, r):
- Find the first stretch that could reach past
l. This is the one atbisect_left(starts, l), or the one before it if it ends strictly afterl. - Walk forward over every stretch starting before
r. - Each visited stretch
[a, b)leaves at most two pieces:[a, l)ifa < l, and[r, b)ifb > r. - Replace the visited stretches with these pieces.
- Find the first stretch that could reach past
- queryRange(l, r): Only the stretch with the largest start not exceeding
lcan cover[l, r), because stretches are disjoint. Find it withbisect_leftand a small adjustment. The answer isTrueif that stretch hasstart <= landend >= r. If no such stretch exists, the answer isFalse.
Why it is correct
The list always holds disjoint stretches in increasing order, and touching stretches are always merged because add uses <= comparisons when absorbing neighbours. A query is true exactly when one stored stretch contains the whole range. Two different stretches cannot jointly cover it, since a gap of at least one real number would separate them. Removal keeps only the parts of the stretches that lie outside [l, r), and these parts never touch each other or other stretches. This is the correct set difference. Stretches that merely touch at l or r are not affected by removal, because the comparisons there are strict.
Complexity
Let N be the number of stored stretches (at most the number of commands).
- Locating the starting position is O(log N) with binary search.
- Each add or remove then visits the stretches it merges or splits. Every command creates at most one net new stretch, so across all commands the number of visited and deleted stretches is amortized O(1) per command.
- Replacing a slice of a Python list costs O(N) in the worst case because elements shift, but this is a fast memory move and is easily fast enough for 20,000 commands.
- Space is O(N).
Reference solution
from bisect import bisect_left
from typing import List, Optional
def track_covered_spans(operations: List[str], arguments: List[List[int]]) -> List[Optional[bool]]:
intervals = []
starts = []
results = []
for operation, args in zip(operations, arguments):
left, right = args
if operation == "addRange":
i = bisect_left(starts, left)
if i > 0 and intervals[i - 1][1] >= left:
i -= 1
new_left = left
new_right = right
j = i
while j < len(intervals) and intervals[j][0] <= new_right:
new_left = min(new_left, intervals[j][0])
new_right = max(new_right, intervals[j][1])
j += 1
intervals[i:j] = [[new_left, new_right]]
starts[i:j] = [new_left]
results.append(None)
elif operation == "queryRange":
i = bisect_left(starts, left)
if i < len(starts) and starts[i] > left:
i -= 1
elif i == len(starts):
i -= 1
covered = i >= 0 and intervals[i][0] <= left and intervals[i][1] >= right
results.append(covered)
elif operation == "removeRange":
i = bisect_left(starts, left)
if i > 0 and intervals[i - 1][1] > left:
i -= 1
j = i
while j < len(intervals) and intervals[j][0] < right:
j += 1
replacement = []
for a, b in intervals[i:j]:
if a < left:
replacement.append([a, left])
if b > right:
replacement.append([right, b])
intervals[i:j] = replacement
starts[i:j] = [a for a, _ in replacement]
results.append(None)
return results