TRT
Sign in
hardAdvancedLeetCode#sorted disjoint intervals#binary search on boundaries

Range module

Track a set of half-open ranges under additions, removals and coverage queries, keeping disjoint intervals sorted.

The Runtime Theory Team1 min read
Taught inB-trees and pagesPro — members onlyA B-tree stores hundreds of keys per node, sized to fit one disk page or a few cache lines, so a tree of billions of keys is only three or four levels tall. Nodes split as they fill, and the tree grows at the root, keeping every leaf at the same depth.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inaddRange(10, 20), removeRange(14, 16), queryRange(10, 14), queryRange(13, 15), queryRange(16, 17)

out[true, false, true]

inaddRange(1, 5), addRange(5, 8), queryRange(2, 7)

out[true]

inaddRange(1, 10), removeRange(1, 10), queryRange(1, 2)

out[false]

Implement addRange(left, right), which tracks every number in [left, right); removeRange(left, right), which stops tracking them; and queryRange(left, right), which returns whether every number in [left, right) is currently tracked. The expected output lists the query results.

Before you code

If the tracked set is stored as sorted, disjoint, non-touching intervals, how many intervals can a single add or remove affect, and how do you find them?

Hints

  1. Store the interval boundaries in one sorted list: even positions are starts, odd positions are ends.
  2. For add and remove, use bisect_left and bisect_right on left and right to find the slice of boundaries to replace, and decide from the parity of the positions which new boundaries to insert.
  3. For query, the range is covered when bisect_right(left) and bisect_left(right) are equal and odd: both ends fall inside the same interval.
  4. A list slice replacement is O(n) in the worst case; a balanced tree or SortedList brings each operation to O(log n) plus the intervals removed.

Production & complexity notes

When solving Range module on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in B-trees and pages to reinforce the underlying pattern.

What it practices

Sorted ranges and boundary searches, the operations behind B+ tree range scans, from B-trees and pages.

Not started

Sign in to save your learning progress.

Sign in to save