Problem 715

Abstract / Summary

A class manages adding removing and checking ranges to efficiently handle overlapping intervals and support range queries.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
88 lines | 2703 bytes | submitted April 22, 2024 | GitHub   26% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (200k+ submissions).

Typical patterns to solve this problem:
  • Design
  • Ordered Set
  • Segment Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. 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
  2. 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
  3. 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 < left the interval lies completely before the new range; low is advanced.
    • If l > right the interval lies completely after; high is set and the loop exits.
    • Otherwise the intervals overlap; the new merged bounds are updated with min and max.
    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)
  4. Replace the overlapped slice - the segment from low to high is 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 == left or l == 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:

  1. Binary search for the first start not less than left.

    pos = bisect_left(self.start, left)
  2. Direct match test - if an interval starts exactly at left, the method verifies that its right endpoint extends beyond right.

    if pos < len(self.start):
        l = self.start[pos]
        r = self.end[pos]
        if l == left and right <= r:
            return True
  3. Check the preceding interval - the candidate that could contain left is the interval immediately before pos. After decrementing pos, the method confirms that left lies within that interval and that right does 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 False because the adjusted pos becomes 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:

  1. Locate the region to examine - the same heuristic as in addRange is 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
  2. Initialize slice boundaries - low marks the first interval that may be affected, high marks the first interval strictly after the removal range.

    low  = pos
    high = len(self.start)
  3. Collect the pieces that survive - the loop walks through intervals from pos onward. For each interval [l, r):

    • If r <= left the interval lies completely before the removal range; low moves forward.
    • If l >= right the interval lies completely after; high is 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) if l < left.
      • The right portion [right, r) if r > right.
    • Both pieces are appended to temporary start and end lists, 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)
  4. Replace the affected slice - the original intervals from low to high are 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 low and high remain 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 if statements (instead of elif) 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 (start and end) enable cache-friendly access patterns; each loop fetches both endpoints together, minimizing indirection.
  • Early termination in both addRange and removeRange stops 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.81 | σ = 1.74

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
32 links | 18 authors | 9 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

3 solutions   April 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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