The O(n) part is what separates people who get it from people who brute-force it.
Use a two-pass elimination strategy: first, find a candidate by iterating through people and eliminating anyone who is known by the current candidate (since a celebrity knows no one). Then, verify the candidate by checking that they are known by everyone else and know no one, returning -1 if verification fails.
Pro tip: During elimination, each knows(a, b) call eliminates exactly one person, so you need at most n-1 calls to find a candidate. This guarantees O(n) calls, and the verification pass adds at most 2(n-1) calls, keeping the total linear.
Confirm that the knows(a, b) API returns true if a knows b, and that a celebrity is known by all others but knows none. Discuss edge cases like n=0, n=1, and multiple potential celebrities.
Initialize candidate = 0. For each person i from 1 to n-1, if knows(candidate, i) is true, then candidate knows i, so candidate cannot be a celebrity; set candidate = i. Otherwise, i knows candidate, so i cannot be a celebrity; keep candidate unchanged.
For every other person i, check that knows(candidate, i) is false (candidate knows no one) and knows(i, candidate) is true (everyone knows candidate). If any check fails, return -1.
Explain that the elimination pass uses at most n-1 calls, and verification uses at most 2(n-1) calls, totaling O(n) API calls. Mention that this is optimal since each call can eliminate at most one person.
If n is 0, return -1. If n is 1, the single person is trivially a celebrity (assuming the definition holds), but verify if needed. Return the candidate index if verification succeeds, otherwise -1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.