Sunteți pe pagina 1din 4

The 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.

We can only ask questions like “does A know B?”

Find the stranger (celebrity) in minimum number of questions.

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.

As “C” does not know anyone but everyone knows “C”.

A naïve solution could be that we scan all the elements of this matrix and search for a row which
contains all “zeros”.

Time complexity will be O(N^2).

The following observations can be made in this problem

 If A knows B, then A can’t be celebrity. Discard A and B may be celebrity.


 I A doesn’t know B, then B can’t be celebrity. Discard B, and A may be celebrity.

We can use these to reduce our comparisons.

We can use stack to verify celebrity.


Push all the celebrities into a stack.

Pop off top two from the stack, discard one person based on return status of knows(A, B).

knows(A, B) = false

(ii) discard B and push A back into stack.

Pop A and C

Knows(A, C) = True

(iii) Discard A and push C back to stack

Pop C and D

Knows(C, D) = false

(iv) Discard D and push C back to stack


Now, just check if “C” is actually the celebrity or not by if everyone knows “C” and C does not know
anyone.

Time complexity O(N)

int findCelebrity (int n)

stack<int> s;

int C; //celebrity

for (int i = 0; i < n; i++)

s.push(i);

int A = s.top( ); //extract top 2

s.pop( );

int B = s.top( );

s.pop( );

while (s.size( ) > 1) //find a potential celebrity

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;

If (knows (C, A))

C = A;

For (int i = 0; i < n; i++) //check if C is actually a celebrity or not

If ( (I != C) &&

(knows(C, i) || !knows(i, C)) )

Return -1;

Return C;

S-ar putea să vă placă și