Find the Celebrity — LeetCode 277 Python Solution

MediumLeetCode PremiumGraphTwo PointersInteractive
Problem
#277
Reading time
3 min

The problem

Suppose you are 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.

Example

Input
graph = [[1,1,0],[0,1,0],[1,1,1]]
Output
1
Explanation
There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody.

Python solution

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
        for i in range(1, n):
            if knows(ans, i):
                ans = i
        for i in range(n):
            if ans != i:
                if knows(ans, i) or not knows(i, ans):
                    return -1
        return ans

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 277. Find the Celebrity is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 277. Find the Celebrity?
LeetCode 277. Find the Celebrity is rated Medium on LeetCode.
What is the time complexity of LeetCode 277. Find the Celebrity?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 277. Find the Celebrity?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 277. Find the Celebrity cover?
LeetCode 277. Find the Celebrity is tagged Graph, Two Pointers and Interactive on LeetCode.
Is LeetCode 277. Find the Celebrity a premium problem?
Yes. LeetCode 277. Find the Celebrity is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview