Imagine you're at an exclusive party with n people labeled from 0 to n-1. Among these party-goers, there might be exactly one celebrity!
A celebrity has a very specific definition:
- ๐ Everyone knows the celebrity (all other n-1 people)
- ๐ The celebrity knows nobody (not a single person at the party)
Your mission is to find this celebrity using the minimum number of questions possible. You can only ask questions in the format: "Hi A, do you know B?"
You have access to a helper function knows(a, b) that returns true if person a knows person b, and false otherwise.
Goal: Return the celebrity's label if one exists, or -1 if there's no celebrity at the party.
Challenge: Can you solve this in less than O(nยฒ) questions?
Input & Output
Visualization
Time & Space Complexity
n-1 questions for elimination phase + 2(n-1) questions for verification = 3n-3 total questions
Only using two pointers and a few variables for tracking
Constraints
- n == graph.length == graph[i].length
- 2 โค n โค 100
- graph[i][j] is 0 or 1
- graph[i][i] == 1 for all i (everyone knows themselves)
- There will be exactly one celebrity in the party if they exist