The Celebrity Problem

medium

In a party of n people, a celebrity is someone whom everyone else knows but who knows no one else. You are given an n x n matrix mat where mat[i][j] = 1 means person i knows person j (and 0 otherwise).

Return the index of the celebrity, or -1 if there is none.

Hints

Testing every person against everyone is O(n^2) — can one comparison rule someone out?
If A knows B, A isn't the celebrity; if A doesn't know B, B isn't the celebrity.
Sweep to a single candidate, then verify it knows no one and is known by all.

Common doubts

A celebrity knows no one and is known by all. mat[A][B]=1 breaks the first for A; mat[A][B]=0 breaks the second for B. Either way one of the two can't be the celebrity.
Elimination guarantees that if a celebrity exists it's the survivor, but not that the survivor is a celebrity. Verification distinguishes 'celebrity' from 'no celebrity'.
No — a celebrity is known by everyone including any other celebrity, but a celebrity knows no one, a contradiction. So the answer is a single index or -1.

Interview follow-ups

Identical algorithm — the elimination and verification just call knows() instead of indexing the matrix, still O(n) queries.
The elimination is n-1 queries and verification up to 2(n-1); careful bookkeeping (reusing known results) trims some, but it stays Theta(n).

Fun facts

  • The celebrity problem is a classic example of solving in O(n) queries what looks like it needs O(n^2).
  • The elimination idea — one comparison removes one candidate — is the same tournament logic used to find a min or max.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: mat = [[0,1,0],[0,0,0],[0,1,0]]
Output: 1
Person 1 knows no one and is known by 0 and 2, so 1 is the celebrity.
Example 2
Input: mat = [[0,1],[1,0]]
Output: -1
Each knows the other, so neither knows no one — there is no celebrity.
Constraints

- 1 <= n <= 3000 - mat[i][j] is 0 or 1 - mat[i][i] = 0

Solve this problem →