# Java 2ms solution that beats 98%, binary search

• There are three cases:

1. when the newInterval is a subspan of one interval, no insertion is needed;
2. when the newInterval is disjoint from all intervals, directly insert it without merge;
3. insertion with merge; using binary search to locate the intervals that newInterval.start and newInterval.end can be merged into.
``````public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
if (intervals == null || newInterval == null) {
return intervals;
}
List<Interval> result = new ArrayList<Interval>();
// binary search for the intervals
int left = 0;
int right = intervals.size() - 1;
int mergeStart = -1; // the interval that can be merged with newInterval.start
int mergeEnd = intervals.size(); // the interval that can be merged with newInterval.end
while (left <= right) {
int mid = left + (right - left) / 2;
if (newInterval.start > intervals.get(mid).end) {
left = mid + 1;
} else if (newInterval.end < intervals.get(mid).start) {
right = mid - 1;
} else if (newInterval.start >= intervals.get(mid).start
&& newInterval.end <= intervals.get(mid).end) {
// no insertion is needed
return intervals;
} else {
mergeStart = mid;
mergeEnd = mid;
// find the right boundary
while (mergeEnd + 1 < intervals.size()
&& newInterval.end >= intervals.get(mergeEnd + 1).start ) {
mergeEnd++;
}
// find the left boundary
while (mergeStart - 1 >= 0
&& newInterval.start <= intervals.get(mergeStart - 1).end ) {
mergeStart--;
}
break;
}
}
if (right == -1) {
// newInterval is smaller than the first interval
mergeEnd = -1;
} else if (left == intervals.size()) {
// newInterval is larger than the last interval
mergeStart = intervals.size();
} else if (left > right) {
// can be inserted between two intervals, no merge is needed
return intervals;
}

// three steps to populate result list
// 1. add intervals before newInterval
// 2. add newInterval, with possible merge
// 3. add intervals after newInterval
for (int i = 0; i < mergeStart; i++) {
}
if (mergeStart >= 0 && mergeStart < intervals.size()) {
newInterval.start = Math.min(newInterval.start, intervals.get(mergeStart).start);
}
if (mergeEnd >= 0 && mergeEnd < intervals.size()) {
newInterval.end = Math.max(newInterval.end, intervals.get(mergeEnd).end);
}