- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 46 lines of Python from the credited upstream file 352.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from sortedcontainers import SortedDict2 3 4class SummaryRanges:5 def __init__(self):6 self.intervals = SortedDict() 7 8 def addNum(self, val: int) -> None:9 if val in self.intervals:10 return11 12 lo = self._lowerKey(val)13 hi = self._higherKey(val)14 15 16 if lo >= 0 and hi >= 0 and self.intervals[lo][1] + 1 == val and val + 1 == hi:17 self.intervals[lo][1] = self.intervals[hi][1]18 del self.intervals[hi]19 20 21 elif lo >= 0 and self.intervals[lo][1] + 1 >= val:22 self.intervals[lo][1] = max(self.intervals[lo][1], val)23 elif hi >= 0 and val + 1 == hi:24 25 self.intervals[val] = [val, self.intervals[hi][1]]26 del self.intervals[hi]27 else:28 self.intervals[val] = [val, val]29 30 def getIntervals(self) -> list[list[int]]:31 return list(self.intervals.values())32 33 def _lowerKey(self, key: int):34 """Returns the maximum key in `self.intervals` < `key`."""35 i = self.intervals.bisect_left(key)36 if i == 0:37 return -138 return self.intervals.peekitem(i - 1)[0]39 40 def _higherKey(self, key: int):41 """Returns the minimum key in `self.intervals` < `key`."""42 i = self.intervals.bisect_right(key)43 if i == len(self.intervals):44 return -145 return self.intervals.peekitem(i)[0]46