public interface InfluencerFinder {
/**
* Given a matrix of following between N LinkedIn users (with ids from 0 to N-1):
* followingMatrix[i][j] == true iff user i is following user j
* thus followingMatrix[i][j] doesn't imply followingMatrix[j][i].
* Let's also agree that followingMatrix[i][i] == false
*
* Influencer is a user who is:
* - followed by everyone else and
* - not following anyone himself
*
* This method should find an Influencer by a given matrix of following,
* or return -1 if there is no Influencer in this group.
*/
int getInfluencer(boolean[][] followingMatrix)
}
Solution from here:
//Logic: a person "i" is not an influencer if "i" is following any "j" or any "j" is not following "i"
//since there could be at most 1 influencer by the nature of the question
//we could maintain a candidate. Whenever we find a counter example, we update the candidate
int getInfluencer(vector<vector<bool> > M) {
int cand=0;
for(int i=1; i<M.size(); i++)
{
if(M[cand][i] == 1 || M[i][cand]==0)
{
cand = i;
}
}
// now verify cand is indeed an influencer
for(int j=0; j<M.size(); j++)
{
if(j==cand) continue;
if(M[cand][j]==1 || M[j][cand]==0) return -1;
}
return cand;
}
//O(n^2) sol
int getInfluencer(vector<vector<bool> > M) {
for(int i=0; i<M.size(); i++) {
bool is_influencer = true;
for(int j=0; j<M.size(); j++) {
if( i==j ) continue;
if( M[i][j] || !M[j][i] ) {
is_influencer = false;
break;
}
}
if( is_influencer )
return i;
}
return -1;
}