My first instinct was the n-squared brute force and I actually started explaining it before catching myself.
Use a two-phase elimination approach: first, find a candidate by iterating through people and eliminating one person per knows(a,b) call, then verify the candidate with at most 2(n-1) additional calls. This reduces the problem from O(n^2) to O(n) API calls.
Pro tip: Explicitly state the worst-case number of API calls (3n-4) and note that the elimination phase is optimal because each call can eliminate at most one person. This shows you understand both correctness and efficiency trade-offs.
Confirm that knows(a,b) returns true if a knows b, and that a celebrity knows no one and is known by everyone. Ask if there can be multiple celebrities (no, at most one) and if n=0 or n=1 edge cases matter.
Initialize candidate = 0. For each person i from 1 to n-1, if knows(candidate, i) is true, then candidate knows someone, so candidate cannot be a celebrity; set candidate = i. Otherwise, i knows candidate, so i cannot be a celebrity; keep candidate. After one pass, candidate is the only possible celebrity.
Check that the candidate knows nobody: for each person i != candidate, if knows(candidate, i) is true, return -1. Also check that everyone knows the candidate: for each person i != candidate, if knows(i, candidate) is false, return -1. If both checks pass, return candidate.
The elimination phase uses n-1 calls, and verification uses at most 2(n-1) calls, totaling 3n-4 calls in the worst case. Explain that this is optimal because each call can eliminate at most one person, and at least n-1 eliminations are needed to identify a unique candidate.
Mention edge cases: n=0 returns -1, n=1 returns 0 (the only person is trivially a celebrity). Discuss that while the algorithm is optimal in calls, it uses O(1) extra space and O(n) time.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.