I was asked the following question:
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
My approach to this problem was to keep adding the numbers to a structure such as a TreeSet which will help with the in-order iteration. While iterating I can check whether the values are consecutive and if they are, I add them to the existing interval, otherwise I create a new interval. Here's the code I have to accomplish it:
public class SummaryRanges {
private TreeSet<Integer> streamNums;
/** Initialize your data structure here. */
public SummaryRanges() {
streamNums= new TreeSet<Integer>();
}
public void addNum(int val) {
if(!streamNums.contains(val)) {
streamNums.add(val);
}
}
public List<Interval> getIntervals() {
ArrayList<Interval> buffer = new ArrayList<Interval>();
if(!streamNums.isEmpty()) {
int start = streamNums.first();
int end = start;
Iterator<Integer> streamIter = streamNums.iterator();
if(streamIter.hasNext()) streamIter.next();
while(streamIter.hasNext()) {
int i = streamIter.next();
if(i == end + 1) {
end = i;
} else {
buffer.add(new Interval(start,end));
start = i;
end = i;
}
}
buffer.add(new Interval(start,end));
}
return buffer;
}
}
It will be great to get some pointers on how to do this better.