Range Module

Hard Design Data Structures Pre-processing + tradeoffs

Range Module is a hard design data structures problem solved with the pre-processing + tradeoffs pattern. The best approach, optimal (sorted map of disjoint intervals), runs in O(log n) per query, amortised O(log n) per update time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from sorted list with linear merging up.

Problem

Build a RangeModule class that keeps track of which numbers are currently covered. Every range is half-open: [left, right) means all real numbers x with left <= x < right, so left is included and right is not.

  • RangeModule() starts with nothing tracked.
  • addRange(left, right) starts tracking every number in [left, right). Some of them may already be tracked; that is fine.
  • queryRange(left, right) returns true if every number in [left, right) is currently tracked, and false otherwise.
  • removeRange(left, right) stops tracking every number in [left, right) that is currently tracked.

Examples

Example 1

Input
RangeModule(), addRange(5, 12), addRange(15, 20), queryRange(6, 10), queryRange(10, 16), addRange(12, 15), queryRange(10, 16)
Output
true, false, true
Why
After the first two calls the tracked numbers are [5, 12) and [15, 20). [6, 10) lies inside [5, 12). [10, 16) needs 12, 13 and 14, which are missing. Adding [12, 15) fills that gap, so all three ranges merge into [5, 20) and the same query now succeeds.

Example 2

Input
RangeModule(), addRange(1, 10), removeRange(4, 6), queryRange(1, 4), queryRange(3, 7), queryRange(6, 10)
Output
true, false, true
Why
Removing [4, 6) splits [1, 10) into [1, 4) and [6, 10). [3, 7) would need 4 and 5, which are gone. Because the ends are open, [1, 4) is still fully tracked even though 4 itself was removed.

Constraints

  • 1 <= left < right <= 10^9
  • At most 10^4 calls in total to addRange, queryRange and removeRange.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Sorted list with linear mergingO(n) per callO(n)
Optimal (sorted map of disjoint intervals)O(log n) per query, amortised O(log n) per updateO(n)

1Sorted list with linear merging

TimeO(n) per callEvery call may walk the whole list of n stored intervals, so q calls take O(q · n) in the worst case.
SpaceO(n)The list of intervals; each call can add at most one new interval.

Keep an ordered list of disjoint, non-touching intervals. Adding walks the list: intervals that end before left are copied, intervals that overlap or touch [left, right) are swallowed into it, and the rest are copied after it. Removing also walks the list, keeping the parts of each interval that fall outside [left, right). A query scans for one interval that contains the whole range.

  1. addRange: copy intervals with end < left, merge every interval with start <= right into [left, right), append it, copy the rest.
  2. removeRange: an interval that ends at or before left, or starts at or after right, is kept whole; otherwise keep its piece before left and its piece after right, if they are not empty.
  3. queryRange: return true if some interval has start <= left and right <= end.
class RangeModule {
    private List<int[]> list = new ArrayList<>();

    public RangeModule() {}

    public void addRange(int left, int right) {
        List<int[]> out = new ArrayList<>();
        int i = 0, n = list.size();
        while (i < n && list.get(i)[1] < left) out.add(list.get(i++));
        while (i < n && list.get(i)[0] <= right) {
            left = Math.min(left, list.get(i)[0]);
            right = Math.max(right, list.get(i)[1]);
            i++;
        }
        out.add(new int[] { left, right });
        while (i < n) out.add(list.get(i++));
        list = out;
    }

    public boolean queryRange(int left, int right) {
        for (int[] iv : list) {
            if (iv[0] <= left && right <= iv[1]) return true;
        }
        return false;
    }

    public void removeRange(int left, int right) {
        List<int[]> out = new ArrayList<>();
        for (int[] iv : list) {
            if (iv[1] <= left || iv[0] >= right) {
                out.add(iv);
            } else {
                if (iv[0] < left) out.add(new int[] { iv[0], left });
                if (iv[1] > right) out.add(new int[] { right, iv[1] });
            }
        }
        list = out;
    }
}

2Optimal (sorted map of disjoint intervals)

TimeO(log n) per query, amortised O(log n) per updateEach call does a constant number of floor lookups and puts. The intervals removed by a clear were each inserted once by an earlier call, so over all calls the clearing costs O(log n) per interval inserted.
SpaceO(n)One map entry per stored interval; a call adds at most two entries.

Store the same disjoint, non-touching intervals in a TreeMap from start to end. floorKey(x) finds the interval that starts at or before x in O(log n), which is the only interval that can contain x. addRange widens [left, right) to swallow the interval around left and the interval around right, deletes every start inside the widened range with one subMap(...).clear(), and puts the merged interval. removeRange first saves the piece of the interval around right that sticks out past right, then cuts the interval around left down to end at left, and finally clears every start in [left, right). A query is one floor lookup. Python, C++ and JavaScript can use a sorted list with binary search (bisect), std::map, or a sorted array with binary search.

  1. addRange: s = floorKey(left); if its end >= left, start the merge at s. t = floorKey(right); if its end > right, end the merge there. Clear the starts in [left, right] and put (left, right).
  2. removeRange: t = floorKey(right); if its end > right, put (right, end). s = floorKey(left); if its end > left, put (s, left). Then clear the starts in [left, right).
  3. queryRange: s = floorKey(left); return s exists and its end >= right.
class RangeModule {
    private final TreeMap<Integer, Integer> map = new TreeMap<>();

    public RangeModule() {}

    public void addRange(int left, int right) {
        Integer s = map.floorKey(left);
        if (s != null && map.get(s) >= left) left = s;
        Integer t = map.floorKey(right);
        if (t != null && map.get(t) > right) right = map.get(t);
        map.subMap(left, true, right, true).clear();
        map.put(left, right);
    }

    public boolean queryRange(int left, int right) {
        Integer s = map.floorKey(left);
        return s != null && map.get(s) >= right;
    }

    public void removeRange(int left, int right) {
        Integer t = map.floorKey(right);
        if (t != null && map.get(t) > right) map.put(right, map.get(t));
        Integer s = map.floorKey(left);
        if (s != null && map.get(s) > left) map.put(s, left);
        map.subMap(left, true, right, false).clear();
    }
}

Edge cases to test

  • Adding a range that only touches an existing one, such as [1, 5) then [5, 9): they must merge so [1, 9) can be queried
  • Adding a range that covers several stored ranges and the gaps between them
  • Removing the middle of one range, which splits it into two pieces
  • Removing a range that does not overlap anything (no change)
  • Querying a range that ends exactly where a stored range ends
  • Querying before anything has been added (always false)

Hints

Hint 1

The numbers go up to 10^9, so a boolean array or a set of single numbers is far too big. Store the tracked numbers as a set of disjoint intervals instead.

Hint 2

Keep the intervals sorted by start and never let two of them overlap or touch. Then a query is true exactly when one single interval covers [left, right).

Hint 3

With a sorted map from start to end you can find the interval that starts at or before a point with one floor lookup. Adding and removing then only touch the intervals inside [left, right], which can be cleared as one sub-map.

FAQ

What is the best time complexity for Range Module?

Optimal (sorted map of disjoint intervals) runs in O(log n) per query, amortised O(log n) per update time and O(n) extra space. Each call does a constant number of floor lookups and puts. The intervals removed by a clear were each inserted once by an earlier call, so over all calls the clearing costs O(log n) per interval inserted.

Which pattern does Range Module use?

It is a design data structures problem that uses the pre-processing + tradeoffs pattern. Other problems with the same pattern: Design Neighbor Sum Service, Simple Bank System, Design File System.

Is there a brute force solution for Range Module?

Yes. Sorted list with linear merging takes O(n) per call time and O(n) space. Keep an ordered list of disjoint, non-touching intervals.

Which edge cases should I test for Range Module?

Adding a range that only touches an existing one, such as [1, 5) then [5, 9): they must merge so [1, 9) can be queried; Adding a range that covers several stored ranges and the gaps between them; Removing the middle of one range, which splits it into two pieces; Removing a range that does not overlap anything (no change); Querying a range that ends exactly where a stored range ends; Querying before anything has been added (always false).