Data Stream as Disjoint Intervals

Keep numbers that arrive one at a time as a sorted list of ranges, joining a range with its neighbours when a new number connects them.

Numbers arrive one at a time. Write a class SummaryRanges with two methods: addNum(int value) adds a number, and getIntervals() returns all the numbers added so far as a list of ranges [start, end]. Each run of consecutive numbers forms one range, the ranges do not overlap, and the list is sorted by start.

Example 1
Input: addNum(1), addNum(3), addNum(7), addNum(2), addNum(6), calling getIntervals() after each
Output: [[1, 1]], [[1, 1], [3, 3]], [[1, 1], [3, 3], [7, 7]], [[1, 3], [7, 7]], [[1, 3], [6, 7]]
Solution

The Idea

A print dialog asks for pages in a short form such as "1-3, 6-7" instead of "1, 2, 3, 6, 7". This problem keeps numbers in the same short form while they arrive. A range like [1, 3] stands for 1, 2 and 3, and such a range of whole numbers is called an interval. "Disjoint" means that no two intervals share a number.

Follow Example 1. After 1, 3 and 7 arrive, none of them sits next to another, so each is an interval on its own: [1, 1], [3, 3] and [7, 7]. Then 2 arrives and fills the gap between 1 and 3, so [1, 1] and [3, 3] become [1, 3]. Last, 6 arrives just below 7, and [7, 7] grows to [6, 7].

So a new number can change the list in different ways. Which intervals do we have to look at to know what happens? Look at the picture below.

Before adding 2, the intervals are [1, 1], [3, 3] and [7, 7]. The left neighbour [1, 1] ends at 2 - 1 and the right neighbour [3, 3] starts at 2 + 1, so after adding 2 they join into [1, 3], next to [7, 7].

In the row labelled "before adding 2", the new number 2 sits between [1, 1], its left neighbour, and [3, 3], its right neighbour. [7, 7] is too far away to matter. In the row labelled "after adding 2", the two neighbours have joined into [1, 3], because [1, 1] ends at 2 - 1 and [3, 3] starts at 2 + 1.

The same is true for every new number: only the interval just before it and the interval just after it can be affected. The number may already be inside the left neighbour. It may touch only the left neighbour, only the right neighbour, or both, or it may touch neither. Each of these five cases is a small, fixed change to the list.

Solution Approach

Keeping every number is the simple way, but it is slow to read back. Keeping intervals instead means settling three things: how to store them, how to find a new number's two neighbours, and what to do in each of the five cases.

Keeping every number

Why not just store every number that arrives? A sorted set would hold 1, 2, 3, 6, 7, and getIntervals could walk through it and start a new interval wherever two numbers differ by more than 1. That is correct, but every call walks all the numbers again, so a run of a million consecutive numbers costs a million steps to report as one interval.

Storing the intervals

Where do the intervals live? A TreeMap, a map in java.util that keeps its keys sorted, holds each interval as an entry from start to end. After Example 1 it holds two entries, 1 to 3 and 6 to 7, and it would still hold two if the intervals covered thousands of numbers. Because the keys are sorted, reading the map from first to last entry gives the list in the order getIntervals needs.

Finding the two neighbours

How do we find the intervals next to a new number? A sorted map can answer "which key comes just before this value?" without walking through every entry. floorEntry(value) returns the entry with the largest start that is at or below value, which is the left neighbour. higherEntry(value) returns the entry with the smallest start above value, which is the right neighbour. Either one is null when no such interval exists.

No other interval can touch value. Every interval before the left neighbour lies further below value, and every interval after the right neighbour lies further above it.

The five cases

What does each case change? If the left neighbour ends at or after value, the number is already covered and nothing changes. If the left neighbour ends at value - 1 and the right neighbour starts at value + 1, the two join: the left entry takes the right one's end, and the right entry is removed.

If only the left neighbour touches, its end becomes value. If only the right neighbour touches, its start becomes value, and since the start is the map's key, the entry is removed and put back under the new key. If neither touches, value becomes the interval [value, value].

Java Solution

The class has three parts, plus a helper for testing:

  • ranges: the TreeMap from start to end, one entry per interval.
  • addNum: finds the neighbours left and right, returns early if value is already covered, and otherwise checks joinsLeft and joinsRight to pick one of the other four cases.
  • getIntervals: copies the entries, already in order, into an int[][].
  • addAll: adds numbers one by one and prints the intervals after each, like the example.

The main method runs Example 1, then a second stream that repeats a number at the end of an interval and in its middle, joins two intervals, and adds a number below all the others.

Java
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class SummaryRanges {

    private final TreeMap<Integer, Integer> ranges = new TreeMap<>();  // start -> end

    public void addNum(int value) {
        Map.Entry<Integer, Integer> left = ranges.floorEntry(value);    // starts at or before
        Map.Entry<Integer, Integer> right = ranges.higherEntry(value);  // starts after

        if (left != null && left.getValue() >= value) {
            return;                                 // value is already inside a range
        }
        boolean joinsLeft = left != null && left.getValue() == value - 1;
        boolean joinsRight = right != null && right.getKey() == value + 1;
        if (joinsLeft && joinsRight) {              // value fills the gap between two ranges
            ranges.put(left.getKey(), right.getValue());
            ranges.remove(right.getKey());
        } else if (joinsLeft) {                     // the left range grows by one at its end
            ranges.put(left.getKey(), value);
        } else if (joinsRight) {                    // the right range grows by one at its start
            ranges.remove(right.getKey());
            ranges.put(value, right.getValue());
        } else {                                    // a range of its own
            ranges.put(value, value);
        }
    }

    public int[][] getIntervals() {
        int[][] result = new int[ranges.size()][];
        int i = 0;
        for (Map.Entry<Integer, Integer> e : ranges.entrySet()) {
            result[i++] = new int[] {e.getKey(), e.getValue()};
        }
        return result;
    }

    static void addAll(SummaryRanges stream, int... values) {
        for (int v : values) {
            stream.addNum(v);
            System.out.println("add " + v + " -> " + Arrays.deepToString(stream.getIntervals()));
        }
    }

    public static void main(String[] args) {
        addAll(new SummaryRanges(), 1, 3, 7, 2, 6);
        System.out.println();
        addAll(new SummaryRanges(), 5, 4, 5, 10, 8, 9, 9, 2);
    }
}

Running it prints:

Output
add 1 -> [[1, 1]]
add 3 -> [[1, 1], [3, 3]]
add 7 -> [[1, 1], [3, 3], [7, 7]]
add 2 -> [[1, 3], [7, 7]]
add 6 -> [[1, 3], [6, 7]]

add 5 -> [[5, 5]]
add 4 -> [[4, 5]]
add 5 -> [[4, 5]]
add 10 -> [[4, 5], [10, 10]]
add 8 -> [[4, 5], [8, 8], [10, 10]]
add 9 -> [[4, 5], [8, 10]]
add 9 -> [[4, 5], [8, 10]]
add 2 -> [[2, 2], [4, 5], [8, 10]]

The first block matches Example 1 line by line. In add 2 -> [[1, 3], [7, 7]] the number 2 joined both neighbours, and in add 6 -> [[1, 3], [6, 7]] it was [7, 7] that moved its start down to 6.

In the second block, add 4 -> [[4, 5]] is the same case as 6: the right neighbour [5, 5] moved its start down. The second add 5 changes nothing, because 5 is already the end of [4, 5]. The first add 9 joins [8, 8] and [10, 10] into [8, 10], and the second add 9 lands in the middle of that interval and changes nothing either. In the last line, 2 has no left neighbour at all, so left is null and 2 becomes an interval of its own at the front.

The early return is easy to leave out, because the other four cases look complete without it. Without it, the second add 5 finds that neither neighbour touches 5 and stores a new interval, so that line prints [[4, 5], [5, 5]], two intervals that share the number 5.

Complexity

The cost depends on k, the number of intervals in the map, not on how many numbers they cover.

  • Time: O(log k) for addNum and O(k) for getIntervals, because addNum does at most two lookups, a remove and a put on the sorted map, each O(log k), while getIntervals copies each of the k entries once.
  • Space: O(k), because the map keeps one entry per interval, so a run of a million consecutive numbers still costs a single entry.

To merge a whole list of intervals at once instead of one number at a time, see Merge Intervals.