## Hi5 Interview Question

Software Engineer / DevelopersOne of the solution is to run BFS but it won't be very efficient. One of the good way to solve this is to look the problem this way. Make a list of friends of A and make another list of friends of C. A and C are 2 degree friends if the two list we have made have at least one friend in common. This intersection can be efficiently done using O(n) time and memory complexity using a hash table.

One of the solution is to run BFS but it won't be very efficieint. One of the good way to solve this is to look the problem this way. Make a list of friends of A and make another list of friends of C. A and C are 2 degree friends if the two list we have made have at least one friend in common. This intersection can be efficiently done using O(n) time and memory complexity using a hash table.

Hi Gaurav,

Can u please tell me are these questions asked on a phone interview or onsite interview?

This can be done in O(1) time after doing a preprocessing using O(n2) space and O(n3) time . suppose Adj is the adjacency matrix of the above graph . So Adj[i][j] is "1" if and only if node "i" and "j" are directly connected .

Now , nodes "k" and "m" are two degree friends if the following condition is true :

if ((adj[k][0] && adj[0][m] ) || (adj[k][1] && adj[1][m] ) ..........|| (adj[k][MAXNODES -1 ] && adj[MAXNODES - 1][m] ) is true .

Consider another 2d array adj2[i][j] which stores the value of above condition for adj[i][j] . adj2 can be calculated as the 'boolean matrix product' of adj with itself . Here 'boolean matrix product' means normal matrix multiplication with "multiplication" operation replaced with "&&" and "plus" operation replaced with "||" operation .

Once adj2 is calculated we can say that "i" and "j" are 2 degree friends if and only if adj2[i][j] is 1.

1. Assuming every person has id, sort friends of A and B O(NlogN)

- Anonymous May 15, 20082. Make sure A and B are not first degree friends. Binary search B in A's friends or vice versa. Return false if found.

3. For every friend in A, do binary search on B's friends O(NlogN). Return true if found, false otherwise.