715. Range Module
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a RangeModule that can track ranges of numbers. We need to support adding a range, removing a range, and querying if a given range is completely covered. The ranges are half-open intervals [left, right). A key challenge is managing a collection of disjoint intervals that can be merged when a new range is added, or split/truncated when a range is removed. The coordinates can be very large, so we must use an interval-based approach rather than tracking individual numbers.
Solution
Range Module in Python
import bisect
class RangeModule:
def __init__(self):
# self.ranges stores a sorted list of disjoint intervals [start, end)
self.ranges = []
def addRange(self, left: int, right: int) -> None:
if left >= right:
return
new_ranges = []
inserted = False
for start, end in self.ranges:
# Current interval is completely to the left of the new one
if end < left:
new_ranges.append([start, end])
# Current interval is completely to the right of the new one
elif start > right:
# If the new/merged interval hasn't been added yet, add it.
if not inserted:
new_ranges.append([left, right])
inserted = True
new_ranges.append([start, end])
# Overlap case: merge intervals
else:
left = min(left, start)
right = max(right, end)
# If the new/merged interval was not inserted (e.g., it's at the end or list was empty)
if not inserted:
new_ranges.append([left, right])
self.ranges = new_ranges
def queryRange(self, left: int, right: int) -> bool:
if left >= right:
return True
# Find the insertion point for an interval starting at 'left'.
# We want the last interval with start <= left.
# bisect_right finds an insertion point which comes after existing entries.
# [left, float('inf')] is used to correctly compare with intervals [s, e]
i = bisect.bisect_right(self.ranges, [left, float('inf')])
# If i is 0, no interval starts at or before 'left'.
if i == 0:
return False
# The candidate interval is at index i - 1.
start, end = self.ranges[i-1]
# Check if this interval covers [left, right).
return end >= right
def removeRange(self, left: int, right: int) -> None:
if left >= right:
return
new_ranges = []
for start, end in self.ranges:
# No overlap, interval is completely outside [left, right)
if end <= left or start >= right:
new_ranges.append([start, end])
# Overlap exists, calculate remaining parts
else:
# If there's a part of the interval before 'left', add it.
if start < left:
new_ranges.append([start, left])
# If there's a part of the interval after 'right', add it.
if end > right:
new_ranges.append([right, end])
self.ranges = new_ranges
Range Module in Java
class RangeModule {
// Use a TreeMap to store disjoint intervals, mapping start to end.
// TreeMap automatically keeps entries sorted by key (start of interval).
private TreeMap<Integer, Integer> intervals;
public RangeModule() {
intervals = new TreeMap<>();
}
public void addRange(int left, int right) {
if (left >= right) return;
// Find an entry that might overlap or be adjacent from the left.
Integer start = intervals.floorKey(left);
if (start == null) {
start = intervals.ceilingKey(left);
}
// Iterate through all intervals that can be merged with [left, right).
while (start != null && start <= right) {
int end = intervals.get(start);
if (end >= left) { // Overlap or adjacency exists
// Merge by updating left and right boundaries.
left = Math.min(left, start);
right = Math.max(right, end);
// Remove the merged interval.
intervals.remove(start);
}
// Move to the next key to check for more merges.
start = intervals.ceilingKey(start);
}
// Put the new merged interval.
intervals.put(left, right);
}
public boolean queryRange(int left, int right) {
if (left >= right) return true;
// Find the entry for an interval that could cover [left, right).
// floorKey(left) gives the greatest key less than or equal to 'left'.
Integer start = intervals.floorKey(left);
// If such an interval exists and its end covers 'right', return true.
return start != null && intervals.get(start) >= right;
}
public void removeRange(int left, int right) {
if (left >= right) return;
// Find an entry that might overlap from the left.
Integer start = intervals.floorKey(left);
if (start == null) {
start = intervals.ceilingKey(left);
}
// To avoid ConcurrentModificationException, we collect changes and apply them later.
TreeMap<Integer, Integer> toAdd = new TreeMap<>();
List<Integer> toRemove = new ArrayList<>();
// Iterate through intervals that could possibly overlap with [left, right).
while (start != null && start < right) {
int end = intervals.get(start);
if (end > left) { // Overlap exists
toRemove.add(start);
// If the interval extends before 'left', keep that part.
if (start < left) {
toAdd.put(start, left);
}
// If the interval extends after 'right', keep that part.
if (end > right) {
toAdd.put(right, end);
}
}
start = intervals.ceilingKey(start + 1);
}
for (int key : toRemove) {
intervals.remove(key);
}
intervals.putAll(toAdd);
}
}
Range Module in C++
class RangeModule {
private:
// Use a map to store disjoint intervals, mapping start to end.
// The map automatically keeps intervals sorted by their start time.
map<int, int> intervals;
public:
RangeModule() {}
void addRange(int left, int right) {
if (left >= right) return;
// Find iterator to the first interval whose start is greater than 'left'.
auto it = intervals.upper_bound(left);
// Check the interval just before 'it' for potential merge.
if (it != intervals.begin()) {
auto prev = std::prev(it);
// If prev interval [s, e) overlaps or is adjacent to [left, right)
if (prev->second >= left) {
// Merge with prev interval
left = min(left, prev->first);
right = max(right, prev->second);
// Erase prev and 'it' will now effectively point to the same position.
// The original 'it' is still valid.
intervals.erase(prev);
}
}
// Merge subsequent overlapping intervals
while (it != intervals.end() && it->first <= right) {
right = max(right, it->second);
it = intervals.erase(it); // Erase and get iterator to the next element
}
// Insert the new merged interval
intervals[left] = right;
}
bool queryRange(int left, int right) {
if (left >= right) return true;
// Find the first interval with start > left.
auto it = intervals.upper_bound(left);
// If there's no interval before it, no range can cover [left, right).
if (it == intervals.begin()) {
return false;
}
// The candidate interval is the one just before 'it'.
auto prev = std::prev(it);
// Check if this candidate interval [s, e) covers [left, right).
// We need s <= left and e >= right. s <= left is guaranteed.
return prev->second >= right;
}
void removeRange(int left, int right) {
if (left >= right) return;
// Find the first interval starting after 'left'.
auto it = intervals.upper_bound(left);
// Also check the interval before 'it' as it might overlap.
if (it != intervals.begin()) {
it = std::prev(it);
}
// Iterate through all intervals that could possibly overlap with [left, right)
while (it != intervals.end() && it->first < right) {
int s = it->first;
int e = it->second;
// If there's no overlap, continue to the next interval.
if (e <= left) {
it++;
continue;
}
// Store parts of the interval that remain and then erase the original.
if (s < left) {
intervals[s] = left; // Truncate the original interval.
}
if (e > right) {
intervals[right] = e; // Add the part after the removed range.
}
// Erase the current interval and move to the next one.
it = intervals.erase(it);
}
}
};
Range Module in TypeScript
class RangeModule {
private ranges: [number, number][];
constructor() {
this.ranges = [];
}
addRange(left: number, right: number): void {
if (left >= right) return;
const newRanges: [number, number][] = [];
let inserted = false;
for (const [start, end] of this.ranges) {
if (end < left) {
newRanges.push([start, end]);
} else if (start > right) {
if (!inserted) {
newRanges.push([left, right]);
inserted = true;
}
newRanges.push([start, end]);
} else {
left = Math.min(left, start);
right = Math.max(right, end);
}
}
if (!inserted) {
newRanges.push([left, right]);
}
this.ranges = newRanges;
}
queryRange(left: number, right: number): boolean {
if (left >= right) return true;
let low = 0, high = this.ranges.length - 1;
let idx = -1;
// Binary search to find the last interval with start <= left
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (this.ranges[mid][0] <= left) {
idx = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
if (idx === -1) {
return false;
}
return this.ranges[idx][1] >= right;
}
removeRange(left: number, right: number): void {
if (left >= right) return;
const newRanges: [number, number][] = [];
for (const [start, end] of this.ranges) {
if (end <= left || start >= right) {
newRanges.push([start, end]);
} else {
if (start < left) {
newRanges.push([start, left]);
}
if (end > right) {
newRanges.push([right, end]);
}
}
}
this.ranges = newRanges;
}
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.