I saw this interview question recently for a firm that said:
Group of people, you can call
Know(i, j)
to ask ifi
th person knowsj
th, the return value istrue
(i
knowsj
) orfalse
(i
does not knowj
). Find the person that everybody else knows him but he knows nobody.
I can think of a O(N^2)
implementation such that you just match every person with the method with every other person, eliminating anyone who actually knows someone. I however cannot think of a faster implementation than this.
Can anyone help or give hints?
There is a simple key to success in interviewing that very few candidates utilize. It is the process of mirroring the personality of the person to whom you are speaking, a process referred to as "Personality Matching." It is based upon the proven fact that we like people who are like us.
“Mirroring” is when a person mimics the body language, verbal habits, or attitudes of someone else, typically unconsciously. Mirroring can relate to personality types because personality traits correlate to many aspects of expression that may be mimicked.
3 golden interview rules: be prepared, be professional, and most importantly, be yourself. The call you've been waiting for has come. A hiring manager wants to interview you.
We can do this in linear time with a simple algorithm. In two lookups, we can eliminate at least one candidate -- pick two persons, and remove person i
with Know(i,j)
or ~Know(j,i)
.
All we have to do is -
Step 1: Find out a person who doesn't know anyone else. Initially every one is our candidate. So let's start with any one i as current node. Iterate over all candidates j. If Knows(i, j) is false. Then j cannot be our candidate. So remove j from candidates. If Knows(i, j) is true for any j, then i cannot be our candidate, so current node will be updated to j, and remove node i. Repeat this until we can't update current node. The last current node is our final candidate. This will be actually O(N) because at each step we are actually removing one node, either i or j.
Step 2: We found a person who doesn't know anyone else. But we've to verify that everyone else knows him. What we can just do is iterate over all the nodes and check, which is O(N). If we found that this is not our node, then there is no such solution. Because there cannot be another node k, which is the solution, as i doesn't know k.
We can use a link list for storing the list of candidates so that removing a candidate will be O(1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With