Data Stream as Disjoint Intervals

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]

Follow up:

What if there are lots of merges and the number of disjoint intervals are small compared to the data stream’s size?

Solution:

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class SummaryRanges {

    TreeSet<Interval> ts;
    
    /** Initialize your data structure here. */
    public SummaryRanges() {
        ts = new TreeSet<>(new Comparator<Interval>(){
            @Override
            public int compare(Interval i1, Interval i2){
                return i1.start-i2.start;
            }
        });
    }
    
    public void addNum(int val) {
        Interval i = new Interval(val, val);
        Interval low = ts.floor(i);
        Interval high = ts.ceiling(i);
        if(low!=null && high!=null && low.end==i.start-1 && high.start==i.end+1){
            i.start = low.start;
            i.end = high.end;
            ts.remove(low);
            ts.remove(high);
            ts.add(i);
        } else if(high!=null && high.start==i.end+1){
            high.start = i.start;
        } else if(low!=null && low.end>=i.start-1){
            low.end = Math.max(low.end, i.end);
        } else {
            ts.add(i);
        }
    }
    
    public List<Interval> getIntervals() {
        return new ArrayList<Interval>(ts);
    }
}

/**
 * Your SummaryRanges object will be instantiated and called as such:
 * SummaryRanges obj = new SummaryRanges();
 * obj.addNum(val);
 * List<Interval> param_2 = obj.getIntervals();
 */
comments powered by Disqus