The Celebrity Problem
Suppose you are at a party with n people labeled 0 to n-1. Among them, there may exist one celebrity: everyone knows the celebrity, but the celebrity knows no one. Given a helper function knows(a, b) that returns true if person a knows person b, find the celebrity or return -1 if none exists. Minimize the number of API calls.
- 2 <= n <= 1000
- knows(a, b) counts as one API call
- There is at most one celebrity
n=3, knows: 0 knows 1, 2 knows 11n=2, nobody knows each other-1n=3, everyone knows everyone-1Suppose you are looking for a celebrity in a crowd of N people. In a brute-force world, you would have to ask everyone about everyone else, which takes N squared questions. But identifying a celebrity has two strict rules that we can use for rapid elimination:
1. A celebrity knows no one.
2. Everyone knows the celebrity.
The magic insight is that the single question "Does Person A know Person B?" always guarantees the death of exactly one suspect. If the answer is Yes, then A cannot be the celebrity (Rule 1). If the answer is No, then B cannot be the celebrity (Rule 2).
Instead of scanning pairwise, we use a Stack to narrow down the suspects.
1. The Setup: Put everyone into the "Suspect Stack."
2. The Face-Off: Pop the top two suspects, A and B. Ask: "Does A know B?"
- If Yes: A is disqualified. Push B back into the stack.
- If No: B is disqualified. Push A back into the stack.
3. The Survivor: Every time we ask a question, one person is removed forever. After N-1 questions, only one person remains in the stack.
4. The Verification: The survivor is our prime suspect, but we haven't proven they are a celebrity yet. We must do a final check: Do they truly know zero people, and does every single other person know them?
stack = [0, 1, ..., n-1]
// Phase 1: Narrow down to 1 candidate
WHILE stack.SIZE > 1:
A = stack.POP()
B = stack.POP()
IF knows(A, B):
stack.PUSH(B) // A is not a celebrity
ELSE:
stack.PUSH(A) // B is not a celebrity
candidate = stack.POP()
// Phase 2: Verify the survivor
FOR i from 0 to n-1:
IF i == candidate: CONTINUE
IF knows(candidate, i) OR NOT knows(i, candidate):
RETURN -1
RETURN candidateThe Celebrity Problem Strategy
Mental Model
If A knows B, A cannot be the celebrity.
If A don't know B, B cannot be the celebrity.
O(N) Complexity
Instead of an O(N²) matrix scan, the elimination tournament strategy finds the truth in linear time by removing one person from contention in every comparison!