{x}
blog image

Find the Celebrity

Solution Explanation:

This problem involves finding a celebrity within a group of n people. A celebrity is someone who is known by everyone else but doesn't know anyone else. We can solve this using two passes:

Pass 1: Potential Celebrity Identification

The first loop iterates through the people, updating ans to be the index of a potential celebrity. The logic is: if ans knows person i, then ans cannot be the celebrity (because a celebrity doesn't know anyone), so we update ans to i. After this loop, ans holds an index that might be the celebrity. It's crucial to note that this doesn't guarantee ans is actually a celebrity; it only identifies a potential candidate.

Pass 2: Celebrity Verification

The second loop verifies if ans is indeed the celebrity. It iterates through all people. For each person i (excluding ans itself), we check two conditions:

  1. knows(ans, i): If ans knows i, then ans is not a celebrity (celebrities don't know anyone).
  2. !knows(i, ans): If i doesn't know ans, then ans is not a celebrity (everyone knows a celebrity).

If either of these conditions is true, then ans is not the celebrity, and the function returns -1. If the loop completes without finding any violations, it means ans satisfies the celebrity criteria, and ans is returned.

Time and Space Complexity Analysis

  • Time Complexity: O(n). The code iterates through the n people twice in the two loops. Each call to knows() is considered a constant-time operation.

  • Space Complexity: O(1). The algorithm uses only a constant amount of extra space to store the variable ans.

Code Explanation (Python):

# The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
 
 
class Solution:
    def findCelebrity(self, n: int) -> int:
        ans = 0
        #Pass 1: Find a potential celebrity
        for i in range(1, n):
            if knows(ans, i):
                ans = i
        #Pass 2: Verify if the potential celebrity is the actual celebrity
        for i in range(n):
            if ans != i:
                if knows(ans, i) or not knows(i, ans):
                    return -1
        return ans

The Python code directly implements the two-pass approach described above. The knows() function (not defined in this code snippet, but provided by LeetCode) is used to determine if one person knows another. The comments clearly delineate the two passes.

The Java, C++, and Go code implementations follow the same logic and have the same time and space complexity as the Python solution. They differ only in syntax and language-specific details.