The Celebrity Problem
Please upvote if you like it!!!!!!!!!!!!
Problem Statement:- A celebrity is a person who is known to all but does not know anyone at a party. If you go to a party of N people, find if there is a celebrity in the party or not. A square NxN matrix M[][] 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 ith person knows jth person. Here M[i][i] will always be 0.
Input:
Output: 1
Explanation: 0th and 2nd person both know 1. Therefore, 1 is the celebrity.
Approach 1: ( Brute force )
Just check each row and column for each index one by one and return accordingly.
~Time Complexity: O(N^2)
Approach 2: ( Optimised using Stack)
~Time Complexity:- O(N)
C++ Code:-
//Function to find if there is a celebrity in the party or not.
bool knows(int a, int b,vector<vector<int> >& M){
if(M[a][b]==1) return true;
return false;
}
int celebrity(vector<vector<int> >& M, int n)
{
// code here
stack<int> st;
for(int i=0;i<n;i++){
st.push(i);
}
while(st.size()>1){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
if(knows(a,b,M))// A knows B
st.push(b);
else
st.push(a);
}
int Candidate=st.top();
//Row check
int rowCount=0;
for(int i=0;i<n;i++){
if(M[Candidate][i]==0)rowCount++;
}
if(rowCount != n) return -1;
//Column check
int colCount=0;
for(int i=0;i<n;i++){
if(M[i][Candidate]==1) colCount++;
}
if(colCount != n-1) return -1;
return Candidate;
}