Problem
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.
A half-open interval [left, right)
denotes all the real numbers x
where left <= x < right
.
Implement the RangeModule
class:
RangeModule()
Initializes the object of the data structure.void addRange(int left, int right)
Adds the half-open interval[left, right)
, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval[left, right)
that are not already tracked.boolean queryRange(int left, int right)
Returnstrue
if every real number in the interval[left, right)
is currently being tracked, andfalse
otherwise.void removeRange(int left, int right)
Stops tracking every real number currently being tracked in the half-open interval[left, right)
.
Examples
Example 1:
|
|
Solution
Method 1 - Using TreeMap
To efficiently track intervals and perform operations like adding, querying, and removing ranges, we can use a Sorted Map (TreeMap in Java or SortedDict in Python). These structures allow for efficient ordering and updates of key-value pairs.
Key Considerations
- A TreeMap/SortedDict structure allows us to maintain intervals in sorted order and easily manage overlaps.
- Add Range: Merge overlapping intervals and add the new range while preserving the sorted order.
- Query Range: Iterate through the intervals to check whether the given range is fully covered by existing intervals.
- Remove Range: Modify or split existing intervals as needed, excluding the range to be removed.
Code
|
|
|
|
Complexity
-
⏰ Time complexity:
addRange
has time complexityO(n)
due to merging intervals.queryRange
has time complexityO(log n)
for traversing and checking.removeRange
has time complexityO(n)
due to modifying intervals.
-
🧺 Space complexity:
O(n)
for storing intervals.