277. Find the Celebrity

Suppose you are at a party withnpeople (labeled from0ton - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the othern - 1people 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.

Note: 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.

Thoughs:

  1. O(3n): Explanation from scy_usc in here
    1. :The first loop will stop to an candidate i who doesn't know anyone from i+1 to n-1. For any previous x<i either know sb else or is not known by sb else.
    2. The second loop will check whether i knows anyone from 0 to i-1.
    3. The third loop is gonna check whether all party participants know x or not.
  2. O(2n): Explanation from czonzhu in here
    1. The first pass is to pick out the candidate. If candidate knows i, then switch candidate.
    2. The second pass is to check whether the candidate is real.

Code

# The knows API is already defined for you.
# @param a, person a
# @param b, person b
# @return a boolean, whether a knows b
# def knows(a, b):

class Solution(object):
    def findCelebrity(self, n):
        """
        :type n: int
        :rtype: int
        """
        ix = 0
        # check if someone knows ix and ix does not know anyone from ix + 1 to n -1
        for i in range(n):
            if knows(ix, i):
                ix = i

        if any(knows(ix, i) for i in range(ix)): return -1 # check if ix knows any one from 0 to ix -1
        if any(not knows(i, ix) for i in range(n)): return -1 # check if everyone else knows ix

        return ix

results matching ""

    No results matching ""