277. Find the Celebrity

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 the celebrity, but the celebrity does not know any of them.



def findCelebrity(n: int):
       
    from functools import lru_cache   
    @lru_cache(maxsize=None)
    def cachedKnows(a, b):
        return knows(a, b)
   
    celeb = 0
   
    for i in range(1, n):
        if cachedKnows(celeb, i):
            celeb = i
   
    for i in range(n):
        if i!=celeb and (not cachedKnows(i, celeb) or cachedKnows(celeb, i)):
            return -1

    return celeb

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break