GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Amazon Question

Given an n-ary tree of resources arranged hierarchically. A process needs to lock a resource node in order to use it. But a node cannot be locked if any of its descendant or ancestor is locked. You are supposed to:

-> write the structure of node
-> write codes for

  • Islock()- returns true if a given node is locked and false if it is not
  • Lock()- locks the given node if possible and updates lock information
  • Unlock()- unlocks the node and updates information.

Codes should be :

  • Islock –O(1)
  • Lock()- O(log n)
  • unLock()- O(log n)
asked Dec 18, 2015 by ApLav 1 flag

The concept in method 2 is not clear. Can anyone explain in words, what is the flow to maintain log n time complexity.it would be great if someone could upload codes in java

1 Answer

struct TreeNode
{
    vector<TreeNode *> child;
    TreeNode * parent;
    
    bool lock;
    int totalDescLock;
    
    TreeNode()
    {
        lock = false;
        totalDescLock = 0;
    }
    
	bool IsLock() 
	{
	    return lock;
	}

	bool Lock()
	{
	    if (totalDescLock > 0)  
	    	return false;
	  
	    TreeNode* temp = parent;
	    while (temp) 
	    {
	        if (temp->IsLock()) 
	            return false;
	        temp = temp->parent;
	    }
	    
	    temp = parent;
	    while(temp) 
	    {
	        temp->totalDescLock++;
	        temp = temp->parent;
	    }
	    lock = true;
	    return lock;
	}

	bool unLock()
	{
		//	Similar to Lock function
		//  Unlock will walk up the path and decrement the totalDescLock count
	}
};

 

answered Dec 18, 2015 by utkarsh111

But the above logic applies with a pre-condition that it should be a height-balanced n-ary tree.

...