Mid
From PDF
Coding
C# Coding Interview
Solve the "Find the Celebrity" problem?
public int FindCelebrity(int n, Func<int, int, bool> knows) {
int candidate = 0;
for (int i = 1; i < n; i++) {
if (knows(candidate, i)) candidate = i;
}
for (int i = 0; i < n; i++) {
if (i != candidate && (knows(candidate, i) || !knows(i,
candidate)))
return -1;
}
return candidate;
}
Explanation:
First find candidate by elimination, then verify candidate.
Follow on:
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png