277.Find the Celebrity

Tags: [trick], [two_pass]

Com: {fb}

Link: https://leetcode.com/problems/find-the-celebrity/\#/description

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.


Solution: Trick, Two Pass

# 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
        """
        candidate = 0
        for i in xrange(1, n):
            if knows(candidate, i):
                candidate = i

        if any([not knows(i, candidate) for i in xrange(n) if candidate != i]):
            # if there is someone doesn't know candidate, return -1
            return -1

        if any([knows(candidate, i) for i in xrange(candidate)]):
            # In the first loop, we have guaranteed that candidate doesn't know the guys who are after him.
            # So here we only need to check does candidate know someone before him.
            return -1

        return candidate

Revelation:

  • See the comments in the code.
  • The straight forward way to find the celebrity is that using two level loops, for example, let 'a' ask all others does 'a' knows someone, and ask do all others know 'a'. In this way, we need call (2 * n^2) times 'knows' function.
  • I the above 'two pass' way, under the worst case, we only need to call (3 * n) times 'knows' function.

Note:

  • Time complexity = O(n).

results matching ""

    No results matching ""