The naive approach is obvious and wrong, O(n^2) calls if you just check every pair.
Use a two-phase elimination approach: first, find a candidate celebrity by iterating through all people and eliminating non-celebrities based on knows(a, b) calls. Then, verify the candidate by checking that everyone knows them and they know no one, using additional API calls. This ensures O(n) calls.
Pro tip: Emphasize that the elimination phase uses exactly n-1 calls, and verification uses at most 2(n-1) calls, so total is O(n). Also, mention edge cases like n=0 or n=1 and how the algorithm handles them.
Start with candidate = 0. This will be the potential celebrity after elimination.
For each person i from 1 to n-1, if knows(candidate, i) is true, then candidate cannot be a celebrity (since they know someone), so set candidate = i. Otherwise, i cannot be a celebrity (since they are not known by candidate), so keep candidate unchanged. This uses n-1 calls.
Verify that the candidate is indeed a celebrity: check that for every other person i, knows(candidate, i) is false and knows(i, candidate) is true. If any check fails, return -1.
If n is 0, return -1. If n is 1, the single person is trivially a celebrity (assuming no self-knows calls), so return 0 after verification (which is trivial).
Explain that elimination uses n-1 calls, verification uses at most 2(n-1) calls, so total O(n) calls, meeting the requirement.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.