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 SummaryRangesaddNum(int value)getIntervals()[start, end]
Example 1
Output: [[1, 1]], [[1, 1], [3, 3]], [[1, 1], [3, 3], [7, 7]], [[1, 3], [7, 7]], [[1, 3], [6, 7]]
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]
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][7, 7][1, 1][3, 3][1, 3][7, 7][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.
In the row labelled "before adding 2", the new number 2 sits between [1, 1][3, 3][7, 7][1, 3][1, 1][3, 3]
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
Storing the intervals
Where do the intervals live? A TreeMapjava.utilgetIntervals
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)valuehigherEntry(value)valuenull
No other interval can touch valuevalue
The five cases
What does each case change? If the left neighbour ends at or after valuevalue - 1value + 1
If only the left neighbour touches, its end becomes valuevaluevalue[value, value]
Java Solution
The class has three parts, plus a helper for testing:
: theranges from start to end, one entry per interval.TreeMap : finds the neighboursaddNum andleft , returns early ifright is already covered, and otherwise checksvalue andjoinsLeft to pick one of the other four cases.joinsRight : copies the entries, already in order, into angetIntervals .int[][] : adds numbers one by one and prints the intervals after each, like the example.addAll
The main
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:
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]]add 6 -> [[1, 3], [6, 7]][7, 7]
In the second block, add 4 -> [[4, 5]][5, 5]add 5[4, 5]add 9[8, 8][10, 10][8, 10]add 9leftnull
The early return is easy to leave out, because the other four cases look complete without it. Without it, the second add 5[[4, 5], [5, 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
and O(k) foraddNum , becausegetIntervals does at most two lookups, a remove and a put on the sorted map, each O(log k), whileaddNum copies each of the k entries once.getIntervals - 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