Python 0715.py
class RangeModule:
def __init__(self):
self.start = [] # sorted list [ left ]
self.end = [] # sorted list [ right ]
def addRange(self, left: int, right: int) -> None:
if not self.start:
self.start = [ left ]
self.end = [ right ]
return
pos = bisect_left(self.start, left)
pos = max(0, pos - 4) # crude heuristic
low = pos # strictly smaller
high = len(self.start) # strictly larger
start = left
end = right
for i in range(pos, len(self.start)):
l = self.start[i]
r = self.end [i]
if r < left:
low = i + 1
elif l > right:
high = i
break
else:
# merge overlapping, may happen several times
start = min(start, l)
end = max(end, r)
self.start[low : high] = [ start ]
self.end [low : high] = [ end ]
def queryRange(self, left: int, right: int) -> bool:
pos = bisect_left(self.start, left)
if pos < len(self.start):
# an interval starts at "left" ?
l = self.start[pos]
r = self.end [pos]
if l == left and right <= r:
return True
# must check previous interval
pos -= 1
if pos < 0:
return False
l = self.start[pos]
r = self.end [pos]
return l <= left and right <= r
def removeRange(self, left: int, right: int) -> None:
# similar to addRange
pos = bisect_left(self.start, left)
pos = max(0, pos - 4) # crude heuristic
low = pos # strictly smaller
high = len(self.start) # strictly larger
# split
start = []
end = []
for i in range(pos, len(self.start)):
l = self.start[i]
r = self.end [i]
if r <= left:
low = i + 1
elif l >= right:
high = i
break
else:
# split or completely remove
if l < left: # we know that r > left
start.append(l)
end .append(left)
if r > right: # we know that l < right
start.append(right)
end .append(r)
# careful: NOT elif instead of if, an existing interval might be split in half
self.start[low : high] = start
self.end [low : high] = end
Difficulty
and has an acceptance rate of about 45% (200k+ submissions).
Typical patterns to solve this problem:
- Design
- Ordered Set
- Segment Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The RangeModule class maintains a dynamic set of integer intervals. Internally it stores two parallel sorted lists: start holds the left endpoints and end holds the corresponding right endpoints. All operations-adding, querying, and removing ranges-rely on binary search (bisect_left) to locate the region of interest and then adjust the stored intervals in place. The design keeps the interval representation compact by merging overlapping intervals on insertion and by splitting intervals only when necessary during removal.
Initialization
The constructor creates empty lists ready for sorted insertion.
def __init__(self):
self.start = [] # sorted list [ left ]
self.end = [] # sorted list [ right ]
At this point the module represents an empty set of ranges.
Adding a Range
The addRange method inserts a new interval [left, right) and merges it with any existing intervals that intersect or touch it.
Key steps:
-
Fast path for the first interval - when the lists are empty the new interval is stored directly.
if not self.start: self.start = [ left ] self.end = [ right ] return -
Locate insertion point - a binary search finds the first stored start that is not less than
left. A small backward offset (max(0, pos - 4)) is applied as a heuristic to reduce the scan length when the exact position lies a few slots earlier.pos = bisect_left(self.start, left) pos = max(0, pos - 4) # crude heuristic -
Determine the span of overlapping intervals - the loop iterates from the heuristic start index to the end of the lists. For each interval
[l, r)it classifies the relationship to[left, right):- If
r < leftthe interval lies completely before the new range;lowis advanced. - If
l > rightthe interval lies completely after;highis set and the loop exits. - Otherwise the intervals overlap; the new merged bounds are updated with
minandmax.
low = pos high = len(self.start) start = left end = right for i in range(pos, len(self.start)): l = self.start[i] r = self.end[i] if r < left: low = i + 1 elif l > right: high = i break else: start = min(start, l) end = max(end, r) - If
-
Replace the overlapped slice - the segment from
lowtohighis replaced by a single merged interval using slice assignment, preserving the sorted order without extra copying.self.start[low : high] = [ start ] self.end [low : high] = [ end ]
Edge Cases Handled
- Adding a range that exactly matches an existing interval results in no change because the overlap detection merges without altering the stored bounds.
- Adding a range that touches an existing interval at its endpoint (
r == leftorl == right) is treated as overlapping, ensuring the intervals become contiguous. - The heuristic start index never becomes negative, guaranteeing safe iteration even when the binary search returns
0.
Querying a Range
The queryRange method checks whether the entire interval [left, right) is covered by the stored ranges.
Key steps:
-
Binary search for the first start not less than
left.pos = bisect_left(self.start, left) -
Direct match test - if an interval starts exactly at
left, the method verifies that its right endpoint extends beyondright.if pos < len(self.start): l = self.start[pos] r = self.end[pos] if l == left and right <= r: return True -
Check the preceding interval - the candidate that could contain
leftis the interval immediately beforepos. After decrementingpos, the method confirms thatleftlies within that interval and thatrightdoes not exceed its right endpoint.pos -= 1 if pos < 0: return False l = self.start[pos] r = self.end[pos] return l <= left and right <= r
Edge Cases Handled
- Queries for a range that starts before any stored interval return
Falsebecause the adjustedposbecomes negative. - Queries that exactly match the left endpoint of an interval succeed without needing to examine the previous interval.
- Queries that fall entirely inside a larger stored interval are correctly identified by the final return statement.
Removing a Range
The removeRange method deletes the interval [left, right) from the stored set, potentially splitting existing intervals.
Key steps:
-
Locate the region to examine - the same heuristic as in
addRangeis used to start the scan a few positions before the binary search result.pos = bisect_left(self.start, left) pos = max(0, pos - 4) # crude heuristic -
Initialize slice boundaries -
lowmarks the first interval that may be affected,highmarks the first interval strictly after the removal range.low = pos high = len(self.start) -
Collect the pieces that survive - the loop walks through intervals from
posonward. For each interval[l, r):- If
r <= leftthe interval lies completely before the removal range;lowmoves forward. - If
l >= rightthe interval lies completely after;highis set and the loop stops. - Otherwise the interval overlaps the removal range. The method may emit up to two new intervals:
- The left portion
[l, left)ifl < left. - The right portion
[right, r)ifr > right.
- The left portion
- Both pieces are appended to temporary
startandendlists, ensuring that a single interval that straddles the removal range is split into two distinct intervals.
start = [] end = [] for i in range(pos, len(self.start)): l = self.start[i] r = self.end[i] if r <= left: low = i + 1 elif l >= right: high = i break else: if l < left: # left side remains start.append(l) end.append(left) if r > right: # right side remains start.append(right) end.append(r) - If
-
Replace the affected slice - the original intervals from
lowtohighare replaced by the newly constructed pieces, preserving order.self.start[low : high] = start self.end [low : high] = end
Edge Cases Handled
- Removing a range that does not intersect any stored interval leaves the data unchanged because
lowandhighremain unchanged and the slice assignment replaces the region with an empty list. - Removing a range that exactly matches an existing interval eliminates that interval without leaving remnants.
- When the removal range cuts through the middle of an interval, the code creates two separate intervals, correctly handling the split.
- The use of two independent
ifstatements (instead ofelif) ensures that both left and right remnants are captured when an interval spans the removal range.
Performance Optimizations
The implementation leverages several techniques to keep operations efficient:
- Binary search (
bisect_left) provides logarithmic positioning within the sorted endpoint lists, dramatically reducing the number of elements examined compared to a linear scan. - Heuristic backward offset (
max(0, pos - 4)) anticipates that the true start of overlap may lie a few positions earlier, allowing the subsequent loop to begin closer to the relevant region while still guaranteeing correctness. - Slice assignment (
self.start[low:high] = [...]) updates the underlying lists in place, avoiding the overhead of constructing new list objects for the entire interval set. - Parallel arrays (
startandend) enable cache-friendly access patterns; each loop fetches both endpoints together, minimizing indirection. - Early termination in both
addRangeandremoveRangestops the scan as soon as an interval is found that lies completely after the target range, preventing unnecessary iteration over the tail of the list.
These choices collectively ensure that the module scales well as the number of stored intervals grows, maintaining fast response times for all supported operations.
ELI5 - Simplified Explanation
Imagine keeping a record of long ribbons laid out on a table. Sometimes you want to tape new pieces of ribbon down, sometimes you want to check if a specific spot is covered, and other times you want to cut a piece of the ribbon away.
The lists named start and end act like two shelves that hold the beginning and finishing points of your ribbons. When you add a new piece, the code looks at the ribbons already on the table. If your new ribbon overlaps with ones that are already there, the code merges them into one single, longer piece of ribbon so they stay nice and tidy.
When you ask to check a spot, the code looks through the lists to see if any of your ribbons cover the area you are interested in. It checks the starting and ending points to make sure your spot is safely tucked inside one of the pieces you have laid down.
Removing a piece of ribbon is like using scissors to cut out a section. The code looks for any ribbon that your cut might touch. If the cut hits the middle of a ribbon, the code splits that ribbon into two smaller pieces or trims the ends so that only the part you wanted to take away disappears, leaving the rest of the ribbon behind.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Go | Python | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java, Python | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 352: Data Stream as Disjoint Intervals
- problem 2158: Amount of New Area Painted Each Day
Solved On The Same Day
- problem 691: Stickers to Spell Word
- problem 757: Set Intersection Size At Least Two
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality