Amazon Interview Question
Software Engineer in TestsCountry: United States
Interview Type: In-Person
So you mean to say you are not using the conventional tree. Rather your tree nodes will have an extra variable which will store the pointer to its parent.
First, there is no such thing as a "conventional tree". Second, read the question. It clearly expects you to come up with some structure yourself.
Islock is possible in O(1)
Considering the general tree data structure with a father field and a locked boolean variable
Lock (node, root)
{
p=node;
do{
while(p!=NULL)
{ push(p);
if(islock(p))
{print cant be lockd and return false}
p=p->child;
}
p=pop(stack);
p=p->next;
}while(p!=NULL or not empty stack)
p=node;
if(p!=root)
{
p=p->father;
if(islock(p))
{print cant be lockd and return false}
}
node->locked=true;
return true;
}
O(log n)
Initially I locked node 40. And then I want to lock the root node 50, then it should verify all nodes below ROOT right?
50
20 60
10 30 70
25 35
32 40
Yes it should verify all the nodes below Root because the number you locking is the root. The point is the way it is doing it. O(5 * log (n) ) would be the case
Sorry... U r right... In that case it depends on the location of the node that needs to be locked. higher the hierarchy of the resource, complexity increases
class NodeLockUnlock:
def __init__(self, d):
self.val = d
self.left = self.right = self.parent = None
self.Count_of_locked_descendants = 0
self.isLocked = False
def isLock(self):
return self.isLocked
def _increase_lock_count_ancestor(self):
node = self
while node:
node.Count_of_locked_descendants += 1
def _decrease_lock_count_ancestor(self):
node = self
while node:
node.Count_of_locked_descendants -= 1
def lock(self):
cur = self
while cur and not cur.isLocked:
cur = cur.parent
if cur == None and self.Count_of_locked_descendants == 0:
self.isLocked = True
self._increase_lock_count_ancestor()
return True
return False
def unLock(self):
self.isLocked = False
self._decrease_lock_count_ancestor()
return True
The tree will look something like this
The IsLocked method will just check the flag;
The Lock method would walk up the path and increment the _numDescendantsLocked variable.
Something like
Unlocked will walk up the path and decrement the _numDescendantsLocked count.
- Anonymous September 08, 2011Methods can be written better etc, but you get the idea.