Identify Celebrity
Suppose you are at a party withn
people (labeled from0
ton - 1
) and among them, there may exist one celebrity. The definition of a celebrity is that all the othern - 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 is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
You are given a helper functionbool knows(a, b)
which tells you whether A knows B. Implement a functionint findCelebrity(n)
, your function should minimize the number of calls toknows
.
Notice
There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return-1
.
Have you met this question in a real interview?
Yes
Example
Given n =2
2 // next n * (n - 1) lines
0 knows 1
1 does not know 0
return1
// 1 is celebrity
"""
The knows API is already defined for you.
@param a, person a
@param b, person b
@return a boolean, whether a knows b
you can call Celebrity.knows(a, b)
"""
#thinking process
#we can do the check for every one, the one that satisfied the requirement, will be the one
#however, during this time, we have repeated the check multiple times
#and we don't do anything if the check result is false
#so if we see when we check a knows b,
# 1. the answer is yes. then it means a must not be celebrity
# 2. the answer is no. then it means b must not be celebrity
#and since we can remove 1 at each check, so after n-1 check, there will only be one person
#we can return that value as the problem stated that there will be exactly 1 celebrity
#there could be no celebrity at all, so we do have to check if that one last person is a celebrity
#follow up: what if there could be multiple celebrities and definition is except celebrity, everyone knows it, and it doesn't know anyone. it can't use this method, n^2
class Solution:
# @param {int} n a party with n people
# @return {int} the celebrity's label or -1
def findCelebrity(self, n):
# Write your code here
cel = 0
for i in xrange(1, n):
if Celebrity.knows(cel, i):
cel = i
for i in xrange(n):
if i == cel:
continue
if not Celebrity.knows(i, cel) or Celebrity.knows(cel, i):
return -1
return cel