03(Aug) The Celebrity Problem
03. The Celebrity Problem
The problem can be found at the following link: Question Link
Problem Description
A celebrity is a person who is known to all but does not know anyone at a party. A party is being organized by some people. A square matrix mat is used to represent people at the party such that if an element of row i and column j is set to 1, it means the ith person knows the jth person. You need to return the index of the celebrity at the party; if the celebrity does not exist, return -1.
Note: Follow 0-based indexing.
Example:
Input:
mat = [[0, 1, 0],
[0, 0, 0],
[0, 1, 0]]Output:
1Explanation: 0th and 2nd person both know 1. Therefore, 1 is the celebrity.
My Approach
Finding the Potential Celebrity:
Initialize the
potential_celebrityto 0.Iterate through the matrix. If
mat[potential_celebrity][i]is 1, it means the currentpotential_celebrityknowsi, so updatepotential_celebritytoi.
Validating the Potential Celebrity:
Iterate through the matrix again to confirm that the
potential_celebritydoesn't know anyone and everyone knows thepotential_celebrity.If any person doesn't know the
potential_celebrityor thepotential_celebrityknows someone, return -1.
Return:
Return the
potential_celebrityif they are confirmed as the celebrity; otherwise, return -1.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the matrix to find and confirm the celebrity.
Expected Auxiliary Space Complexity: O(1), as we use a constant amount of additional space.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated