Find a Celebrity from a Knows Matrix
SalesforceSoftware Engineer · OnsiteLast updated
Find a celebrity in a knows matrix with linear candidate elimination followed by complete verification that the candidate knows nobody and is known by everyone else.
Problem
Among n people, a celebrity knows nobody else and is known by everybody else. Determine the celebrity's index, or return -1 if no celebrity exists.
Function Contract
Implement find_celebrity(knows), where knows[a][b] is true exactly when person a knows person b.
Rules
- A person's diagonal entry is irrelevant.
- A valid celebrity
csatisfiesknows[c][i] == falseandknows[i][c] == truefor everyi != c. - Return
-1rather than an unverified candidate. - Use
O(1)auxiliary space beyond the input.
Constraints
0 <= n <= 10000.- The matrix is square.
- Target
O(n)matrix lookups rather than checking every ordered pair.
Examples
knows = [
[false, true, true],
[false, false, true],
[false, false, false]
]
output = 2
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.