Data Stream as Disjoint Intervals

Maintain disjoint sorted intervals under add(int) and getIntervals() via a std::map keyed by start.

Hard
Time O(log n) per add Space O(n)
LeetCode
6 min read
intervals ordered-map

Problem#

Implement SummaryRanges supporting addNum(int) and getIntervals(). Maintain the list of disjoint intervals covering all values added so far.

Examples#

  • addNum(1); addNum(3); getIntervals() → [[1,1],[3,3]]
  • After addNum(2): getIntervals() → [[1,3]]

Constraints#

  • Up to 3 * 10^4 ops.

Hints#

Hint 1
Keep a std::map<int,int> keyed by start, value = end. Each add looks up neighboring intervals and possibly merges.

Approach#

std::map<int,int> ordered by interval start. On addNum(x): find the interval whose start ≤ x (upper_bound then step back). Decide whether x extends it, lies inside it (no-op), or is disjoint. Then check whether the right neighbor’s start equals x + 1 and merge.

Solution#

Data Stream as Disjoint Intervals
class SummaryRanges {
map<int,int> mp; // start -> end
public:
void addNum(int x) {
auto next = mp.upper_bound(x);
auto prev = next == mp.begin() ? mp.end() : prev_iter(next);
// Case: x already covered by previous interval.
if (prev != mp.end() && prev->second >= x) return;
bool mergePrev = (prev != mp.end() && prev->second + 1 == x);
bool mergeNext = (next != mp.end() && next->first == x + 1);
if (mergePrev && mergeNext) {
prev->second = next->second;
mp.erase(next);
} else if (mergePrev) {
prev->second = x;
} else if (mergeNext) {
int ne = next->second;
mp.erase(next);
mp[x] = ne;
} else {
mp[x] = x;
}
}
vector<vector<int>> getIntervals() {
vector<vector<int>> out;
out.reserve(mp.size());
for (auto& [s, e] : mp) out.push_back({s, e});
return out;
}
private:
static map<int,int>::iterator prev_iter(map<int,int>::iterator it) { return --it; }
};

Editorial#

Four cases on each add: covered, merge-with-prev only, merge-with-next only, merge-both, fresh interval. The ordered map gives O(log n) for the neighbor lookup; the rest is O(1). getIntervals is O(n) one-shot.

Complexity#

  • Time: O(log n) per add; O(n) for getIntervals.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.