← Microsoft Interview Insights
The linear pass to narrow down a candidate clicked pretty fast for me.
Use a two-pass elimination strategy: first, find a candidate by iterating through all people and eliminating anyone who is known by the current candidate. Then, verify the candidate by checking that they know no one and everyone else knows them. This uses at most 2n-2 calls, achieving O(n).
Pro tip: Mention that the elimination pass is essentially a tournament where each comparison eliminates one person, and the verification pass is necessary to handle false positives. This shows you understand the invariant and edge cases.
Start with person 0 as the initial candidate.
For each person i from 1 to n-1, if knows(candidate, i) is true, then candidate knows i, so candidate cannot be the celebrity; set candidate = i. Otherwise, i knows candidate, so i cannot be the celebrity; keep candidate unchanged.
After the loop, verify that the candidate is indeed a celebrity: check that for every other person j, knows(candidate, j) is false and knows(j, candidate) is true. If any check fails, return -1.
If verification passes, return the candidate; otherwise, return -1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.