Saturday, October 31, 2020

Find the Celebrity

Problem: Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.

Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).

You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.

Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.


Approach: Use two pointers. One from the start say A and one from the end B. Initial values of A and B are 0 and n - 1 respectively. Now have a loop:

  • WHILE A < B
    • IF Knows(A, B) 
      • A = A + 1 // A knows B so A can't be a celebrity
    • ELSE
      • B = B - 1 // A doesn't know B so B can't be celebrity
At the end we will get a potential candidate (=  A or B as A and B will be same at the end of loop). Now we will run another loop from i = 0 to n - 1 and check if each and every ith person, where i is not equals to candidate, knows candidate and candidate does not know i. If for every i this condition is satisfied then the candidate is celebrity otherwise we can safely tell that there are no celebrity in the party:

  • For i = 0 to n - 1
    • IF i != candidate AND (Knows(candidate, i) OR !Knows(i, candidate))
      • return -1
  • return candidate

Implementation in C#:

        public static int FindCelebrity(int n)

        {
            if (n == 0)
            {
                return -1;
            }

            int a = 0, b = n - 1;

            while(a < b)
            {
                if (Knows(a, b))
                {
                    ++a;
                }
                else
                {
                    --b;
                }
            }
            
            // Get the potential candidate, now check if it is really a celebrity or not 
            return IsCandidateIsCelebrity(n, a) ? a : -1;
        }

        private static bool IsCandidateIsCelebrity(int n, int candidate)
        {
            for (int i = 0; i < n; ++i)
            {
                if (i != candidate && (!Knows(i, candidate) || Knows(candidate, i)))
                {
                    return false;
                }
            }

            return true;
        }


Complexity: O(n)

No comments:

Post a Comment