Find the Celebrity - 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.

Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: "Hi, A. Do you know B?" to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).

You are given an integer n and a helper function bool knows(a, b) that tells you whether a knows b. Implement a function int findCelebrity(n).

There will be exactly one celebrity if they are at the party. Return the celebrity's label if there is a celebrity at the party. If there is no celebrity, return -1.

Note: The n x n 2D array graph given as input is not directly available to you, and instead only accessible through the helper function knows. graph[i][j] == 1 represents person i knows person j, whereas graph[i][j] == 0 represents person i does not know person j.

Input & Output

Example 1 — Celebrity Exists
$ Input: n = 3, graph = [[1,1,0],[0,1,0],[1,1,1]]
Output: 1
💡 Note: Person 1 is the celebrity: Person 0 knows 1, Person 2 knows 1, but Person 1 only knows themselves (diagonal doesn't count)
Example 2 — No Celebrity
$ Input: n = 2, graph = [[1,1],[1,1]]
Output: -1
💡 Note: Both people know each other, so neither can be a celebrity (celebrity should know nobody)
Example 3 — Single Person
$ Input: n = 1, graph = [[1]]
Output: 0
💡 Note: With only one person, they are trivially the celebrity (knows no one else, everyone else knows them - vacuous truth)

Constraints

  • 1 ≤ n ≤ 100
  • graph.length == n
  • graph[i].length == n
  • graph[i][j] is 0 or 1
  • graph[i][i] == 1

Visualization

Tap to expand
Find the Celebrity Problem01CELEBRITY2Celebrity Definition:• Everyone knows the celebrity• Celebrity knows nobody elsePerson 1 is the celebrity!Use elimination strategy: O(n) time, O(1) space
Understanding the Visualization
1
Input
n people and adjacency matrix showing who knows whom
2
Process
Use elimination strategy to find candidate, then verify
3
Output
Return celebrity's ID or -1 if no celebrity exists
Key Takeaway
🎯 Key Insight: Each knows() call eliminates exactly one person, leading to optimal O(n) solution
Asked in
Facebook 25 Google 18 Amazon 15 Microsoft 12
89.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen