Range Module solution explained

Range Module asks for a class that tracks half-open ranges of numbers: add a range, remove a range, and ask whether a range is fully tracked. Keep the tracked ranges as a sorted list of disjoint intervals, merging on add and splitting on remove. The neatest version stores only the boundaries in one sorted array, where even positions open a range and odd positions close one; two binary searches find the slice to replace, so a query is O(log n) and an update is O(log n) plus the cost of replacing the slice.

By Published 9 min read

The problem, restated

Build a class with three methods. addRange(left, right) starts tracking every real number x with left <= x < right. removeRange(left, right) stops tracking every number in that span. queryRange(left, right) returns true only if every number in [left, right) is currently tracked. Calls arrive in any order, and ranges can overlap, touch or swallow each other.

An operation sequence written for this page (results printed by the code below)
CallResultTracked afterwards
addRange(10, 20)[10, 20)
addRange(30, 40)[10, 20), [30, 40)
queryRange(12, 18)trueunchanged
queryRange(15, 35)falseunchanged: [20, 30) is missing
addRange(20, 30)[10, 40), the three pieces merge
queryRange(15, 35)trueunchanged
removeRange(25, 32)[10, 25), [32, 40), one range split in two
queryRange(24, 26)falseunchanged
queryRange(32, 40)trueunchanged
removeRange(0, 100)nothing
queryRange(10, 11)falsenothing
An operation sequence written for this page (results printed by the code below). Scroll sideways on a small screen.

What the interviewer is checking

Range Module is a test of invariants. If you promise that the stored ranges are always sorted, disjoint and not touching, then each method becomes short: a query is answered by the single range that could contain left, an add absorbs every range it meets, and a remove trims the ranges at its two ends and drops the ones in between. Interviewers watch for the two classic bugs, failing to merge touching ranges and failing to split a range on remove, and for a sensible conversation about cost per operation.

Questions to settle first

  • Are intervals half-open? Yes, so [10, 20) and [20, 30) together cover [10, 30) without a gap.
  • Is coverage about integers or all real numbers? Real numbers, which is why touching ranges must merge but ranges with any gap must not.
  • What is the mix of operations? Many queries and few updates favors binary search over a sorted array.
  • Can left equal right? Assume left < right on every call, and say so.

A small-range baseline

With integer endpoints in a small range, you could keep a set of unit cells [x, x + 1) and add, remove or check each cell. That costs O(right - left) per call and fails for wide ranges, but it is a reliable reference to test the real solution against, and this page's tests used exactly that.

Approach 1: a sorted list of disjoint ranges

Store ranges as [start, end] pairs, sorted and disjoint. For an add, walk the list: ranges ending before left stay, ranges starting after right stay, and every range in between is absorbed by widening [left, right). For a remove, any range that overlaps [left, right) keeps only the parts outside it, which may be a left piece, a right piece, both or neither. For a query, look for one stored range that contains the whole request.

class RangeModule:
    def __init__(self):
        self.ranges = []

    def addRange(self, left, right):
        out, placed = [], False
        for s, e in self.ranges:
            if e < left:
                out.append([s, e])
            elif s > right:
                if not placed:
                    out.append([left, right])
                    placed = True
                out.append([s, e])
            else:
                left, right = min(left, s), max(right, e)
        if not placed:
            out.append([left, right])
        self.ranges = out

    def removeRange(self, left, right):
        out = []
        for s, e in self.ranges:
            if e <= left or s >= right:
                out.append([s, e])
                continue
            if s < left:
                out.append([s, left])
            if e > right:
                out.append([right, e])
        self.ranges = out

    def queryRange(self, left, right):
        return any(s <= left and right <= e for s, e in self.ranges)
Python: interval list, O(n) per update and query.

Look at the two comparisons that decide overlap. In addRange the test is e < left, so a range ending exactly at left is absorbed and touching ranges merge. In removeRange the test is e <= left, so a range ending exactly at left is untouched, because the half-open removal does not reach it. Swapping these is the most common bug in this problem.

Approach 2: one sorted array of boundaries

Flatten the ranges into a single sorted array of edges: [10, 25, 32, 40] means [10, 25) and [32, 40) are tracked. A binary search position tells you where a value falls: an odd position means inside a tracked range, an even one means outside. Every update replaces the slice of edges between two binary search positions with at most two new edges, and parity decides which ones.

  • Add [left, right). Let i be the leftmost insertion point of left and j the rightmost insertion point of right. Replace edges[i:j] with left if i is even (left falls outside, so it opens a range) and right if j is even (right falls outside, so it closes one).
  • Remove [left, right). Same positions, opposite parity: keep left if i is odd (it now closes the range it cut) and right if j is odd (it reopens the rest).
  • Query [left, right). Let i be the rightmost insertion point of left and j the leftmost insertion point of right. The span is fully tracked when i equals j and i is odd: no edge lies strictly inside, and left sits inside a range.
from bisect import bisect_left, bisect_right

class RangeModuleEdges:
    def __init__(self):
        self.edges = []

    def addRange(self, left, right):
        i = bisect_left(self.edges, left)
        j = bisect_right(self.edges, right)
        piece = []
        if i % 2 == 0:
            piece.append(left)
        if j % 2 == 0:
            piece.append(right)
        self.edges[i:j] = piece

    def removeRange(self, left, right):
        i = bisect_left(self.edges, left)
        j = bisect_right(self.edges, right)
        piece = []
        if i % 2 == 1:
            piece.append(left)
        if j % 2 == 1:
            piece.append(right)
        self.edges[i:j] = piece

    def queryRange(self, left, right):
        i = bisect_right(self.edges, left)
        j = bisect_left(self.edges, right)
        return i == j and i % 2 == 1
Python: boundary list with bisect. O(log n) query; update is O(log n) plus the slice replacement.
function lowerBound(arr, x) {
  let lo = 0;
  let hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (arr[mid] < x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

function upperBound(arr, x) {
  let lo = 0;
  let hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (arr[mid] <= x) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

class RangeModule {
  constructor() {
    this.edges = [];
  }

  update(left, right, keepParity) {
    const i = lowerBound(this.edges, left);
    const j = upperBound(this.edges, right);
    const piece = [];
    if (i % 2 === keepParity) piece.push(left);
    if (j % 2 === keepParity) piece.push(right);
    this.edges.splice(i, j - i, ...piece);
  }

  addRange(left, right) {
    this.update(left, right, 0);
  }

  removeRange(left, right) {
    this.update(left, right, 1);
  }

  queryRange(left, right) {
    const i = upperBound(this.edges, left);
    const j = lowerBound(this.edges, right);
    return i === j && i % 2 === 1;
  }
}
JavaScript: the boundary list with hand-written binary searches.

Why bisect_left for left and bisect_right for right on updates? Using the leftmost position for left and the rightmost for right pulls any edge equal to left or right into the replaced slice. On an add that removes the shared edge between [10, 20) and a new [20, 30), so they merge. On a remove it removes an edge that is about to be re-added with the same value, which keeps the array free of duplicate edges.

Complexity

n stored ranges, k ranges absorbed or cut by one update
ApproachqueryRangeaddRange / removeRangeMemory
Unit cells (small integer range only)O(right - left)O(right - left)O(range size)
Interval list, linear walkO(n)O(n)O(n)
Boundary array with binary searchO(log n)O(log n) to find, O(n) worst case to shiftO(n)
Balanced tree map of start to endO(log n)O((k + 1) log n)O(n)
n stored ranges, k ranges absorbed or cut by one update. Scroll sideways on a small screen.

The O(n) shift in the boundary array is a memory move, which is fast in practice. If the interviewer wants a strict logarithmic bound per range touched, describe a balanced tree map from start to end (TreeMap in Java, std::map in C++): find the floor entry for left, absorb or trim the k entries that overlap, and insert at most two.

Edge cases

  • Adding a range that touches an existing one at an endpoint must merge them; a later query across the join must return true.
  • Removing from the middle of one range must leave two ranges.
  • Removing a range that starts or ends exactly on a stored edge must not leave a zero-length range behind.
  • Querying a range that is tracked except for a single gap of any width must return false.
  • Adding a range already fully covered, or removing one that is not tracked, must change nothing.

Common mistakes

  • Using the same comparison for add and remove, which either fails to merge touching ranges or trims ranges the removal does not reach.
  • Answering a query by checking only that left and right are each tracked. [10, 25) and [32, 40) both contain points of [24, 33), but the span has a hole.
  • Forgetting that remove can split one range into two.
  • Sorting the list after every add instead of keeping it sorted, which hides an O(n log n) step in each call.
  • In the boundary version, using bisect_right for left on updates. Adding [20, 30) to [10, 20) then gives edges [10, 20, 20, 30], and a query for [15, 25) wrongly returns false.

How to explain it out loud

Fictional example

Stating the invariant before writing methods
Candidate
I will keep the tracked ranges sorted, disjoint and not touching. With that, any span that is fully tracked must sit inside one stored range, so a query is a lookup of the range that could contain left.
Candidate
Add absorbs every range it overlaps or touches. Remove trims the ranges it cuts and may split one into two. Both keep the invariant.
Interviewer
Can queries be faster than linear?
Candidate
If I flatten the ranges into a sorted array of edges, binary search gives a position, and odd positions are inside a range. Then a query is two binary searches and a parity check.

Data Stream as Disjoint Intervals keeps the same kind of merged interval set, but it only ever adds single numbers. My Calendar II is a design class over half-open ranges that counts depth instead of merging. Employee Free Time reads the gaps between merged busy ranges, which is what a removeRange-heavy module would expose.

Practicing with Natively

Practice saying the invariant first; it is what makes the three methods short. During a mock interview on Mac or Windows, Natively transcribes your explanation so you can hear later whether the invariant came before the code, and once you have your own version it can read the problem from a screenshot and suggest a different representation, such as the boundary array, to compare. Learn more about the AI interview assistant.

Questions people ask

How do you solve Range Module?

Keep tracked ranges sorted, disjoint and not touching. Add absorbs every range it overlaps or touches, remove trims overlapping ranges and may split one in two, and a query checks whether one stored range contains the whole span.

What is the boundary array trick in Range Module?

Store all range edges in one sorted array. A binary search position that is odd means inside a tracked range. Each update replaces the slice between two search positions with at most two edges chosen by parity.

What is the time complexity of Range Module?

With the boundary array, queries are O(log n) and updates are O(log n) plus an array shift. A balanced tree map gives O((k + 1) log n) per update for k ranges touched.

Why do touching ranges have to merge?

Intervals are half-open, so [10, 20) and [20, 30) together cover [10, 30) with no gap. If they stay separate, a query across 20 would wrongly fail.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP