Tutorialspoint
Problem
Solution
Submissions

Find the Celebrity in a Party

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to find the "celebrity" in a party represented as a directed graph. A celebrity is defined as a person who is known by everyone but doesn't know anyone. The party is represented as a matrix where M[i][j] = 1 means person i knows person j, and M[i][j] = 0 means person i doesn't know person j.

Example 1
  • Input: [ [0, 1, 0], [0, 0, 0], [1, 1, 0] ]
  • Output: 1
  • Explanation:
    • Person 0 knows person 1 but doesn't know person 2.
    • Person 1 doesn't know anyone.
    • Person 2 knows persons 0 and 1.
    • Therefore, person 1 is the celebrity since everyone knows them, and they know no one.
Example 2
  • Input: [ [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 1, 0] ]
  • Output: 2
  • Explanation:
    • Person 0 knows person 2.
    • Person 1 knows person 2.
    • Person 2 doesn't know anyone.
    • Person 3 knows person 2.
    • Therefore, person 2 is the celebrity.
Constraints
  • 1 ≤ n ≤ 10^4 (where n is the number of people at the party)
  • M[i][j] is either 0 or 1
  • M[i][i] = 0 (a person doesn't know themselves)
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysWalmartArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • The brute force approach would be to check each person, requiring O(n^2) time
  • Use the elimination method to find a potential celebrity
  • Verify the potential celebrity knows no one and everyone knows them
  • Remember, there can be at most one celebrity, or none at all

Steps to solve by this approach:

 Step 1: Start by assuming person 0 is the celebrity.

 Step 2: For each person i (from 1 to n-1), check if the candidate knows i.
 Step 3: If the candidate knows i, then the candidate cannot be the celebrity, so update the candidate to i.
 Step 4: After this elimination process, verify if the final candidate is truly a celebrity.
 Step 5: Check if the candidate knows no one and everyone knows the candidate.
 Step 6: If the verification passes, return the candidate. Otherwise, return -1 indicating no celebrity exists.
 Step 7: This approach works because each comparison eliminates one person from being a celebrity.

Submitted Code :