Range Module

Track tracked half-open intervals — std::map keyed by start, with merge/split on add/remove and predecessor lookup for queries.

Hard
Time O(log n + k) amortized per op Space O(n)
LeetCode
8 min read
design intervals ordered-map

Problem#

Maintain a set of half-open intervals supporting addRange(l,r), removeRange(l,r), and queryRange(l,r) (true iff the whole [l,r) is currently tracked).

Examples#

  • addRange(10,20); removeRange(14,16); queryRange(10,14)true.
  • queryRange(13,15)false; queryRange(16,17)true.

Constraints#

  • 1 <= l < r <= 10^9, up to 10^4 ops.

Approach#

Store intervals in std::map<int,int> keyed by start, value = end. On add, find overlaps via lower_bound, merge them. On remove, split any straddling interval. On query, find the first interval starting <= l and check that its end >= r.

Solution#

Range Module
class RangeModule {
map<int,int> mp; // start -> end (half-open)
public:
void addRange(int left, int right) {
auto it = mp.lower_bound(left);
if (it != mp.begin()) {
auto p = prev(it);
if (p->second >= left) { left = p->first; right = max(right, p->second); it = p; }
}
while (it != mp.end() && it->first <= right) {
right = max(right, it->second);
it = mp.erase(it);
}
mp[left] = right;
}
bool queryRange(int left, int right) {
auto it = mp.upper_bound(left);
if (it == mp.begin()) return false;
--it;
return it->second >= right;
}
void removeRange(int left, int right) {
auto it = mp.lower_bound(left);
if (it != mp.begin()) {
auto p = prev(it);
if (p->second > left) {
int s = p->first, e = p->second;
mp[s] = left;
if (e > right) mp[right] = e;
it = mp.lower_bound(left);
}
}
while (it != mp.end() && it->first < right) {
if (it->second <= right) it = mp.erase(it);
else { int e = it->second; mp.erase(it); mp[right] = e; break; }
}
}
};

Editorial#

Half-open [l, r) lets touching intervals merge cleanly without off-by-one drama. The ordered map’s lower_bound plus a single backward step locates the candidate that might contain left — that’s all you need for both queries and merges.

Complexity#

  • Time: O(log n + k) amortized; total intervals only shrinks across adds.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.