Skip to problem
←

The Celebrity Problem

Hard 0 attempts

At a party of N people, a celebrity is someone whom every other person knows, but who knows no one else themselves. Using a function knows(a, b) that tells you whether person a knows person b, identify the celebrity if one exists, or return -1 if there isn't one.

People are labeled 0 through n - 1. Return that zero-based label. Ignore whether a person knows themselves.

Examples display a matrix where row a, column b is 1 exactly when a knows b. Your function receives a callable knows(a, b), not the matrix itself. Knowledge need not be mutual.

Function contract

Implement findCelebrity(n, knows). The fixture supplies a 0/1 matrix; the editor passes it as a knows(a,b) function.

Output: Return the zero-based celebrity label, or -1 if no celebrity exists.

Example 1

Input
n = 3
knows = [[0,1,0],[0,0,0],[0,1,0]]
Output
1

Example 2

Input
n = 2
knows = [[0,1],[1,0]]
Output
-1
Constraints
  • 2 <= n <= 500
  • People are labeled 0 through n - 1
  • The fixture is an n × n matrix of 0s and 1s; entry [a][b] indicates whether a knows b
  • Self-knowledge entries on the diagonal are ignored
Topics

Candidate Elimination

For each new person i, one comparison rules someone out: if the current candidate knows i, the candidate cannot be a celebrity; otherwise i cannot be one. The surviving candidate still needs verification, checking both that they know nobody else and that everyone else knows them.

javascript
function findCelebrity(n, knows) {
  let candidate = 0;
  for (let i = 1; i < n; i++) if (knows(candidate, i)) candidate = i;
  for (let i = 0; i < n; i++) {
    if (i === candidate) continue;
    if (knows(candidate, i) || !knows(i, candidate)) return -1;
  }
  return candidate;
}

Time: O(n) calls to knows, at most 3(n - 1).

Auxiliary space: O(1), excluding the provided fixture.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript