Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as Java by Narendra ( 6 years ago )
class MyCalendarTwo {
private Bst bst = null;
public MyCalendarTwo() {
}
public boolean book(int start, int end) {
return validateAndInsert(start, end);
}
/**
* insert the node into #bst only if the given interval is not triple overlapping with existing evetns.
*/
private boolean validateAndInsert(int start, int end) {
if(findOverlapCount(bst, start,end) >= 2) {
return false;
}
insert(start,end);
return true;
}
/**
* Do inorder traversal in that process keep track of the count of
* overlapping intervals with the input interval.
* Stop iterating
* 1) Overlapping count reaches 2
* 2) Or current node's start is < end
**/
private int findOverlapCount(Bst root, int start, int end) {
if(root == null) {
return 0;
}
int lCount = findOverlapCount(root.left, start, end);
// Current element's start is
if(root.start>end || lCount >=2 ) {
return lCount;
}
int cCount = isOverlapping(root, start, end)?1:0;
int rCount = findOverlapCount(root.right, start, end);
return lCount + cCount + rCount;
}
/**
* Insert given interval into BST.
**/
private void insert(int start, int end) {
if(bst == null) {
bst = new Bst(start, end, null, null);
return;
}
Bst itr = bst;
Bst previous = itr;
while(itr != null) {
previous = itr;
if(start <= itr.getStart()) {
itr = itr.getLeft();
} else {
itr = itr.getRight();
}
}
Bst newNode = new Bst(start, end, null, null);
if(start<=previous.getStart()) {
previous.setLeft(newNode);
} else {
previous.setRight(newNode);
}
}
private boolean isOverlapping(Bst node, int s2, int e2) {
int s1 = node.start;
int e1 = node.end;
if(s1<e2 && s2 < e1) {
return true;
}
return false;
}
}
class Bst {
int start;
int end;
Bst left;
Bst right;
public Bst(int start, int end, Bst left, Bst right) {
this.start = start;
this.end = end;
this.left = left;
this.right = right;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public Bst getLeft() {
return left;
}
public Bst getRight() {
return right;
}
public void setLeft(Bst left) {
this.left = left;
}
public void setRight(Bst right) {
this.right = right;
}
}
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* MyCalendarTwo obj = new MyCalendarTwo();
* boolean param_1 = obj.book(start,end);
*/
Revise this Paste