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.

1 variation · 1 problem

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

Candidate Elimination
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;
}

The variations

  1. 1Rule out one person per question

    If cand knows i, cand is not the celebrity; otherwise i is 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.
Next: Re-rooting DP: the answer for every root in O(n) →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.