Count Integers in Intervals

Hard Design Data Structures Pre-processing + tradeoffs

Count Integers in Intervals is a hard design data structures problem solved with the pre-processing + tradeoffs pattern. The best approach, optimal (sorted map of intervals and a running total), runs in O(log n) amortised per add, O(1) per count time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from sorted list with linear merging up.

Problem

Design a CountIntervals class that keeps a growing collection of integer intervals and can tell how many distinct integers they cover.

  • CountIntervals() starts with no intervals.
  • add(left, right) adds the interval [left, right]. Both ends are included, so it covers every integer x with left <= x <= right.
  • count() returns how many integers lie in at least one of the intervals added so far. An integer covered by several intervals is counted only once.

Examples

Example 1

Input
CountIntervals(), add(4, 6), add(10, 12), count(), add(6, 10), count(), add(1, 2), count()
Output
6, 9, 11
Why
[4, 6] holds 4, 5 and 6, and [10, 12] holds 10, 11 and 12, so the first count is 6. Adding [6, 10] overlaps both and fills the gap 7, 8, 9, so everything from 4 to 12 is covered: 9 integers. [1, 2] sits apart from the rest and adds 1 and 2, for 11.

Example 2

Input
CountIntervals(), add(5, 5), add(6, 6), count(), add(1, 100), count(), add(50, 60), count()
Output
2, 100, 100
Why
Two single-number intervals give 2. [1, 100] swallows both, so exactly the integers 1 to 100 are covered. [50, 60] is already inside, so the count does not change.

Constraints

  • 1 <= left <= right <= 10^9
  • At most 10^5 calls in total to add and count.
  • count is called at least once.

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 intervals and a running total)O(log n) amortised per add, O(1) per countO(n)

1Sorted list with linear merging

TimeO(n) per callEach add rebuilds the list and each count scans it, and the list can hold n intervals, so q calls cost O(q · n) in the worst case.
SpaceO(n)The list of intervals; each add creates at most one new interval.

Keep an ordered list of disjoint intervals. To add [left, right], walk the list: intervals that end before left are copied unchanged, intervals that start at or before right overlap the new one and are swallowed into it by stretching left and right, and the rest are copied after the merged interval. count() walks the list once more and adds up right - left + 1 for every interval. Because no two stored intervals overlap, no integer is counted twice.

  1. add: copy every interval whose end is less than left.
  2. While the next interval starts at or before right, set left = min(left, its start) and right = max(right, its end), and skip it.
  3. Append [left, right], then copy the remaining intervals.
  4. count: return the sum of end - start + 1 over the list.
class CountIntervals {
    private List<int[]> list = new ArrayList<>();

    public CountIntervals() {}

    public void add(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 int count() {
        int total = 0;
        for (int[] iv : list) total += iv[1] - iv[0] + 1;
        return total;
    }
}

2Optimal (sorted map of intervals and a running total)

TimeO(log n) amortised per add, O(1) per countEach loop round removes one interval, and every interval is removed at most once after being put by an earlier add, so over all calls the removals cost O(log n) each. Apart from that, an add does one extra lookup and one put.
SpaceO(n)One map entry per stored interval; each add puts exactly one.

Store the same disjoint intervals in a TreeMap from start to end, and keep total, the number of covered integers, up to date at all times. An interval overlaps [left, right] only if it starts at or before right and ends at or after left. Among the intervals that start at or before right, floorEntry(right) gives the one with the largest start, and since the intervals are disjoint and sorted, the overlapping ones are exactly the ones you meet by repeating floorEntry(right) until an interval ends before left. Each one is swallowed: stretch left and right to cover it, subtract its length from total, and remove it. Finally put the merged interval and add its length. count() returns total in O(1). Python and JavaScript can keep two sorted arrays of starts and ends with binary search instead of a tree; C++ can use std::map.

  1. add: e = floorEntry(right).
  2. While e exists and e's end >= left: left = min(left, e's start), right = max(right, e's end), total -= e's length, remove e, and look up floorEntry(right) again.
  3. put(left, right) and add right - left + 1 to total.
  4. count: return total.
class CountIntervals {
    private final TreeMap<Integer, Integer> map = new TreeMap<>();
    private int total = 0;

    public CountIntervals() {}

    public void add(int left, int right) {
        Map.Entry<Integer, Integer> e = map.floorEntry(right);
        while (e != null && e.getValue() >= left) {
            left = Math.min(left, e.getKey());
            right = Math.max(right, e.getValue());
            total -= e.getValue() - e.getKey() + 1;
            map.remove(e.getKey());
            e = map.floorEntry(right);
        }
        map.put(left, right);
        total += right - left + 1;
    }

    public int count() {
        return total;
    }
}

Edge cases to test

  • count before any add: 0
  • A single-number interval, left == right, adds exactly one integer
  • Adding an interval that is already fully covered: the count stays the same
  • Adding an interval that swallows several stored intervals and the gaps between them
  • Intervals that share only an endpoint, such as [1, 5] and [5, 9]: 5 is counted once, for 9 in total
  • Neighbours with no gap, such as [1, 5] and [6, 9]: the count is 9 whether or not they are merged
  • Large ranges: [1, 10^9] alone counts 10^9 integers, so never store the integers one by one

Hints

Hint 1

The ends go up to 10^9, so a set of integers can grow far too big. Store the covered integers as disjoint intervals instead, sorted by start.

Hint 2

When you add [left, right], only the stored intervals that overlap it change: they are all swallowed into one bigger interval. Everything else stays as it is.

Hint 3

Keep a running total of covered integers. When an interval is swallowed, subtract its length; when the merged interval goes in, add its length. Then count() is just the total.

FAQ

What is the best time complexity for Count Integers in Intervals?

Optimal (sorted map of intervals and a running total) runs in O(log n) amortised per add, O(1) per count time and O(n) extra space. Each loop round removes one interval, and every interval is removed at most once after being put by an earlier add, so over all calls the removals cost O(log n) each. Apart from that, an add does one extra lookup and one put.

Which pattern does Count Integers in Intervals 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 Count Integers in Intervals?

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

Which edge cases should I test for Count Integers in Intervals?

count before any add: 0; A single-number interval, left == right, adds exactly one integer; Adding an interval that is already fully covered: the count stays the same; Adding an interval that swallows several stored intervals and the gaps between them; Intervals that share only an endpoint, such as [1, 5] and [5, 9]: 5 is counted once, for 9 in total; Neighbours with no gap, such as [1, 5] and [6, 9]: the count is 9 whether or not they are merged; Large ranges: [1, 10^9] alone counts 10^9 integers, so never store the integers one by one.