N Celebrity Algorithm
N Celebrity Algorithm
N Celebrity Algorithm
In a party of N people, only one person is known to everyone. Such a person may be present in the
party, if yes, (s)he doesn’t know anyone in the party.
Suppose there are 4 people (A, B, C, D) in a party you will be given a Boolean matrix:
Here “1” means that a person in row knows a person in the column. Like A knows C in the first row.
For simplicity in the algorithm we have assumed that a person does not know himself.
By looking at the matrix you can say that “c” is the celebrity.
A naïve solution could be that we scan all the elements of this matrix and search for a row which
contains all “zeros”.
Pop off top two from the stack, discard one person based on return status of knows(A, B).
knows(A, B) = false
Pop A and C
Knows(A, C) = True
Pop C and D
Knows(C, D) = false
stack<int> s;
int C; //celebrity
s.push(i);
s.pop( );
int B = s.top( );
s.pop( );
If (knows(A, B))
A = s.top( );
s.pop( );
Else
B = s.top( );
s.pop( );
C = s.top( );
s.pop( );
if (knows(C, B))
C = B;
C = A;
If ( (I != C) &&
Return -1;
Return C;