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.
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
Edge cases
Verification fails → −1. The elimination pass alone can't detect this.
Sole person is trivially the celebrity — verification passes vacuously.