Find the Celebrity
Among n people, a celebrity is known by everyone and knows no one. Find them with O(n) knows(a,b) queries, or return −1.
Intuition
One question eliminates one person: if a knows b, a isn't a celebrity; if not, b isn't. Run one elimination pass to leave a single candidate, then verify them with 2n more queries.
When every pair could be queried but the answer is unique, look for a question whose answer eliminates one candidate whichever way it goes. knows(a, b) does exactly that: if true, a can't be the celebrity; if false, b can't. One pass of n−1 such questions leaves a single survivor, which you then verify. That eliminate-one-per-question idea is the whole technique.
Approach
Every query kills someone
knows(a,b) true → a is out (celebrities know nobody). False → b is out (everyone knows a celebrity). Either way one candidate drops.
Single survivor
Sweep i from 1..n−1 with a running candidate: if candidate knows i, i becomes the candidate. n−1 queries leave one possibility.
Verify
The elimination proves nobody else can be the celebrity, not that the survivor is. Check the survivor knows no one and everyone knows them.
Solution & live demo
Common pitfalls
Skipping the verification pass
for i in range(1, n):
if knows(cand, i): cand = i
return candfor i in range(n):
if i != cand and (knows(cand, i) or not knows(i, cand)):
return -1
return candThe first pass only proves that everyone else is disqualified — it never proves the survivor qualifies. When no celebrity exists, some candidate still survives, and returning it is wrong. The second pass is what distinguishes "last one standing" from "actually a celebrity".
Comparing the candidate against itself during verification
for i in range(n):
if knows(cand, i) or not knows(i, cand):
return -1for i in range(n):
if i != cand and (knows(cand, i) or not knows(i, cand)):
return -1knows(cand, cand) is undefined by the problem and typically returns False, so not knows(i, cand) fires and a genuine celebrity is rejected. The candidate must be excluded from its own check.
Checking every pair
for a in range(n):
for b in range(n):
...cand = 0
for i in range(1, n):
if knows(cand, i): cand = iThat's O(n²) calls when O(n) suffices to find the candidate. Each query already rules someone out permanently, so re-asking about eliminated people is wasted work.
Edge cases
Verification fails → −1. The elimination pass alone can't detect this.
Sole person is trivially the celebrity — verification passes vacuously.