Skip to content

Instantly share code, notes, and snippets.

@madhur
Last active June 9, 2019 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madhur/cf68b1083e4b298d014520ca5cfefb40 to your computer and use it in GitHub Desktop.
Save madhur/cf68b1083e4b298d014520ca5cfefb40 to your computer and use it in GitHub Desktop.
Merge intervals
public static ArrayList<Interval> insertRange(ArrayList<Interval> intervalsList, Interval insert) {
ArrayList<Interval> out = new ArrayList<>();
for(Interval i: intervalsList){
if(i.end < insert.start) {
out.add(i);
}
else if(i.start > insert.end) {
out.add(insert);
insert = i;
}
else if(i.start <= insert.end || i.end >= insert.start){
int newStart = Math.min(i.start, insert.start);
int newEnd = Math.max(i.end, insert.end);
insert = new Interval(newStart, newEnd);
}
}
out.add(insert);
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment