Question : Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals. Let th
My implementation using BST. O(logn) to merge: Inorder traversal gives you updated intervals.
private static Interval add(Interval root, Interval x){
if(root == null)
return x;
if(root.start >= x.start){
root.left = add(root.left,x);
if(mergeLeft(root,root.left)){
root.left = null;
}
}
else{
root.right = add(root.right,x);
if(mergeRight(root,root.right)){
root.right = null;
}
}
return root;
}
private static boolean mergeLeft(Interval root,Interval left){
if(left.end < root.start)
return false;
else{
root.start = Math.min(root.start, left.start);
root.end = Math.max(root.end, left.end);
return true;
}
}
private static boolean mergeRight(Interval root,Interval right){
if(right.start > root.end)
return false;
else{
root.start = Math.min(root.start, right.start);
root.end = Math.max(root.end, right.end);
return true;
}
}