Find the Celebrity — LeetCode 277 Python Solution
- Problem
- #277
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(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.