Manager Teammate relationship
Anonymous User
625

Given a file that has two kinds of statements.
X is manager of Y.
A is teammate of B.

Statements can come in any order and file is huge.

Design the ds which stores this relationship so that the following queries are supported.

  1. Who is manager of A.
  2. Who are suboordinates of A.
  3. Who are teammates of A.

Sample I/P:
C is teammate of D.
X is teammate of Y.
A is manager of C
A is manager of X.

The expected o/p for the above i/p:
A is manager of C,D,X,Y and C,D,X,Y are all teammates.

I had given the following pseudo code:

class Node {
	String id;
	Node parent;
	Set<Node> peers;
	Set<Node> children;
}
Map<String,Node> cache;

handleManager( String parent, String child){
   initialize if not present: parent, child
   Node parentNode = cache.get(parent);
   Node childNode = cache.get(child);
   
   childNode.parent = parentNode;
   
   Set<Node> peers = new HashSet<>();
   peers.addAll(childNode.peers);
   peers.addAll(parentNode.children);
   
   for(Node thisNode: peers){
      thisNode.peers = peers;
	  thisNode.parent = parentNode;
   }
   
   parentNode.children = peers;
   
}

handleTeammate(String peer1, String peer2){
   initialize peer1 and peer2.
   Node peer1Node = cache.get(peer1);
   Node peer2Node = cache.get(peer2);

   Set<Node> peers = new HashSet<>();
   peers.addAll(peer1Node.peers);
   peers.addAll(peer2Node.peers);
   
   peers.add(peer1Node);
   peers.add(peer2Node);
   
   Node parent = null
   for(Node thisPeer: peers){
         if(thisPeer.parent != null && parent == null){
			 parent = thisPeer.parent;
		 }
		 thisPeer.peers = peers;
   }
   for(Node thisPeer: peers){
	   thisPeer.parent = parent;
   }
   parent.children= peers;
    
}

Obviously this is not optimized one. Looking for suggestions

Comments (4)