Graphs · Pattern 11 of 14
Candidate elimination: one pass to rule people out
Every question "does a know b?" rules out one person. One pass leaves a single candidate; a second pass checks that the candidate really is the celebrity.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Find the one node everyone points to and that points to no one
- An O(n²) adjacency matrix, but only O(n) questions allowed
The template
int findCelebrity(int n) {
int cand = 0;
for (int i = 1; i < n; i++)
if (knows(cand, i)) cand = i; // cand knows someone: cand is out
for (int i = 0; i < n; i++) // check the survivor
if (i != cand && (knows(cand, i) || !knows(i, cand))) return -1;
return cand;
} def find_celebrity(n):
cand = 0
for i in range(1, n):
if knows(cand, i): # cand knows someone: cand is out
cand = i
for i in range(n): # check the survivor
if i != cand and (knows(cand, i) or not knows(i, cand)):
return -1
return cand int findCelebrity(int n) {
int cand = 0;
for (int i = 1; i < n; i++)
if (knows(cand, i)) cand = i; // cand knows someone: cand is out
for (int i = 0; i < n; i++) // check the survivor
if (i != cand && (knows(cand, i) || !knows(i, cand))) return -1;
return cand;
} function findCelebrity(n) {
let cand = 0;
for (let i = 1; i < n; i++)
if (knows(cand, i)) cand = i; // cand knows someone: cand is out
for (let i = 0; i < n; i++) // check the survivor
if (i !== cand && (knows(cand, i) || !knows(i, cand))) return -1;
return cand;
} The variations
-
1Rule out one person per question
If
candknowsi, cand is not the celebrity; otherwiseiis not (the celebrity is known by all). After n − 1 questions one candidate remains. Verify it in a second pass.
Mistakes to avoid
- Skipping the second pass: the survivor is only the one person who might be the celebrity, not proof that one exists.
- In the first pass, also asking whether i knows cand. One question per person is enough to rule someone out.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.