Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 8, 2017 03:47
Show Gist options
  • Select an option

  • Save shailrshah/b6c3a4a666559fe9def422fd20d4e7f8 to your computer and use it in GitHub Desktop.

Select an option

Save shailrshah/b6c3a4a666559fe9def422fd20d4e7f8 to your computer and use it in GitHub Desktop.
Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do i…
// if A knows B -> A is definately not a celeb, B is a candidate
// 1. Finalize on a candidate
// 2. Confirm that everyone knows him and candidate knows no one
public int findCelebrity(int n) {
int candidate = 0;
for(int i = 0; i < n; i++)
candidate = knows(candidate, i) ? i : candidate;
for(int i = 0; i < n; i++) {
if(!knows(i, candidate)) return -1;
if(i != candidate && knows(candidate, i)) return -1;
}
return candidate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment