The Celebrity Problem - GeeksforGeeks

24 Apr, 2022
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 the minimum number of questions.We can describe the problem input as an array of numbers/characters representing persons in the party. We also have a hypothetical function HaveAcquaintance(A, B) which returns true if A knows B, false otherwise. How can we solve the problem. 
Examples:  
Input:
MATRIX = { {0, 0, 1, 0},
           {0, 0, 1, 0},
           {0, 0, 0, 0},
           {0, 0, 1, 0} }
Output:id = 2
Explanation: The person with ID 2 does not 
know anyone but everyone knows him

Input:
MATRIX = { {0, 0, 1, 0},
           {0, 0, 1, 0},
           {0, 1, 0, 0},
           {0, 0, 1, 0} }
Output: No celebrity
Explanation: There is no celebrity.
We measure the complexity in terms of calls made to HaveAcquaintance().
Method 1: This uses Graph to arrive at the particular solution.
Approach: Model the solution using graphs. Initialize indegree and outdegree of every vertex as 0. If A knows B, draw a directed edge from A to B, increase indegree of B and outdegree of A by 1. Construct all possible edges of the graph for every possible pair [i, j]. There are NC2 pairs. If a celebrity is present in the party, there will be one sink node in the graph with outdegree of zero and indegree of N-1.  
Algorithm: 
Create two arrays indegree and outdegree, to store the indegree and outdegreeRun a nested loop, the outer loop from 0 to n and inner loop from 0 to n.For every pair i, j check if i knows j then increase the outdegree of i and indegree of jFor every pair i, j check if j knows i then increase the outdegree of j and indegree of iRun a loop from 0 to n and find the id where the indegree is n-1 and outdegree is 0
Create two arrays indegree and outdegree, to store the indegree and outdegree
Run a nested loop, the outer loop from 0 to n and inner loop from 0 to n.
For every pair i, j check if i knows j then increase the outdegree of i and indegree of j
For every pair i, j check if j knows i then increase the outdegree of j and indegree of i
Run a loop from 0 to n and find the id where the indegree is n-1 and outdegree is 0
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find celebrity#include <bits/stdc++.h>#include <list>using namespace std;  // Max # of persons in the party#define N 8  // Person with 2 is celebritybool MATRIX[N][N] = {{0, 0, 1, 0},                    {0, 0, 1, 0},                    {0, 0, 0, 0},                    {0, 0, 1, 0}};  bool knows(int a, int b){    return MATRIX[a][b];}  // Returns -1 if celebrity// is not present. If present,// returns id (value from 0 to n-1).int findCelebrity(int n){    //the graph needs not be constructed    //as the edges can be found by    //using knows function         //degree array;    int indegree[n]={0},outdegree[n]={0};         //query for all edges    for(int i=0; i<n; i++)    {        for(int j=0; j<n; j++)        {            int x = knows(i,j);                         //set the degrees            outdegree[i]+=x;            indegree[j]+=x;        }    }         //find a person with indegree n-1    //and out degree 0    for(int i=0; i<n; i++)    if(indegree[i] == n-1 && outdegree[i] == 0)        return i;         return -1;}  // Driver codeint main(){    int n = 4;    int id = findCelebrity(n);    id == -1 ? cout << "No celebrity" :               cout << "Celebrity ID " << id;    return 0;}
// Java program to find celebrityimport java.util.*;class GFG {   // Max # of persons in the party  static final int N = 8;   // Person with 2 is celebrity  static int MATRIX[][] = { { 0, 0, 1, 0 },                           { 0, 0, 1, 0 },                           { 0, 0, 0, 0 },                           { 0, 0, 1, 0 } };   static int knows(int a, int b) { return MATRIX[a][b]; }   // Returns -1 if celebrity  // is not present. If present,  // returns id (value from 0 to n-1).  static int findCelebrity(int n)  {     // the graph needs not be constructed    // as the edges can be found by    // using knows function     // degree array;    int[] indegree = new int[n];    int[] outdegree = new int[n];     // query for all edges    for (int i = 0; i < n; i++)    {      for (int j = 0; j < n; j++)      {        int x = knows(i, j);         // set the degrees        outdegree[i] += x;        indegree[j] += x;      }    }     // find a person with indegree n-1    // and out degree 0    for (int i = 0; i < n; i++)      if (indegree[i] == n - 1 && outdegree[i] == 0)        return i;     return -1;  }   // Driver code  public static void main(String[] args)  {    int n = 4;    int id = findCelebrity(n);    if (id == -1)      System.out.print("No celebrity");    else      System.out.print("Celebrity ID " + id);  }} // This code is contributed by Rajput-Ji
# Python3 program to find celebrity # Max # of persons in the partyN = 8 # Person with 2 is celebrityMATRIX = [ [ 0, 0, 1, 0 ],           [ 0, 0, 1, 0 ],           [ 0, 0, 0, 0 ],           [ 0, 0, 1, 0 ] ]            def knows(a, b):       return MATRIX[a][b] def findCelebrity(n):         # The graph needs not be constructed    # as the edges can be found by    # using knows function           # degree array;    indegree = [0 for x in range(n)]    outdegree = [0 for x in range(n)]           # Query for all edges    for i in range(n):        for j in range(n):            x = knows(i, j)                           # Set the degrees            outdegree[i] += x            indegree[j] += x           # Find a person with indegree n-1    # and out degree 0    for i in range(n):        if (indegree[i] == n - 1 and           outdegree[i] == 0):            return i                 return -1     # Driver code   if __name__ == '__main__':         n = 4    id_ = findCelebrity(n)         if id_ == -1:        print("No celebrity")    else:        print("Celebrity ID", id_) # This code is contributed by UnworthyProgrammer
// C# program to find celebrityusing System;public class GFG{   // Max # of persons in the party  static readonly int N = 8;   // Person with 2 is celebrity  static int[,] MATRIX = { { 0, 0, 1, 0 },                           { 0, 0, 1, 0 },                           { 0, 0, 0, 0 },                           { 0, 0, 1, 0 } };   static int knows(int a, int b) { return MATRIX[a,b]; }   // Returns -1 if celebrity  // is not present. If present,  // returns id (value from 0 to n-1).  static int findCelebrity(int n)  {     // the graph needs not be constructed    // as the edges can be found by    // using knows function     // degree array;    int[] indegree = new int[n];    int[] outdegree = new int[n];     // query for all edges    for (int i = 0; i < n; i++)    {      for (int j = 0; j < n; j++)      {        int x = knows(i, j);         // set the degrees        outdegree[i] += x;        indegree[j] += x;      }    }     // find a person with indegree n-1    // and out degree 0    for (int i = 0; i < n; i++)      if (indegree[i] == n - 1 && outdegree[i] == 0)        return i;     return -1;  }   // Driver code  public static void Main(String[] args)  {    int n = 4;    int id = findCelebrity(n);    if (id == -1)      Console.Write("No celebrity");    else      Console.Write("Celebrity ID " + id);  }} // This code is contributed by aashish1995
<script> // JavaScript program to find celebrity     // Max # of persons in the party      var N = 8;     // Person with 2 is celebrity    var MATRIX = [ [ 0, 0, 1, 0 ],                   [ 0, 0, 1, 0 ],                   [ 0, 0, 0, 0 ],                   [ 0, 0, 1, 0 ] ];     function knows(a , b) {        return MATRIX[a][b];    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    function findCelebrity(n) {         // the graph needs not be constructed        // as the edges can be found by        // using knows function         // degree array;        var indegree = Array(n).fill(0);        var outdegree = Array(n).fill(0);         // query for all edges        for (var i = 0; i < n; i++) {            for (j = 0; j < n; j++) {                var x = knows(i, j);                 // set the degrees                outdegree[i] += x;                indegree[j] += x;            }        }         // find a person with indegree n-1        // and out degree 0        for (i = 0; i < n; i++)            if (indegree[i] == n - 1 && outdegree[i] == 0)                return i;         return -1;    }     // Driver code             var n = 4;        var id = findCelebrity(n);        if (id == -1)            document.write("No celebrity");        else            document.write("Celebrity ID " + id); // This code is contributed by todaysgaurav </script>
Output : 
Celebrity ID 2
Complexity Analysis: 
Time Complexity: O(n2). A nested loop is run traversing the array, SO the time complexity is O(n2)
Space Complexity: O(n). Since extra space of size n is required.
Approach : The problem can be solved using recursion. Say, if the ‘potential celebrity’ of N-1 persons is known, can the solution to N be found from it? A potential celebrity is one who is the only one left after eliminating n-1 people. n-1 people are eliminated with the following strategy: 
If A knows B, then A cannot be a celebrity. But B could be.
Else If B knows A, then B cannot be a celebrity. But A could be.
The above-mentioned approach use Recursion to find the potential celebrity among n persons, recursively calls n-1 persons, till the base case of 0 persons is reached. For 0 persons -1 is returned indicating that there are no possible celebrities since there are 0 people. In the ith stage of recursion, the ith person and (i-1)th person are compared to check if anyone of them knows the other. And using the above logic (in the bullet points) the potential celebrity is returned to the (i+1)th stage.
Once the recursive function returns an id. We check if this id does not know anybody else, but all others know this id. If this is true, then this id will be the celebrity.
Algorithm : 
Create a recursive function that takes an integer n.Check the base case, if the value of n is 0 then return -1.Call the recursive function and get the ID of the potential celebrity from the first n-1 elements.If the id is -1 then assign n as the potential celebrity and return the value.If the potential  celebrity of first n-1 elements knows n-1 then return n-1, (0 based indexing)If the celebrity of first n-1 elements does not know n-1 then return id of celebrity of n-1 elements, (0 based indexing)Else return -1Create a wrapper function and check whether the id returned by the function is really the celebrity or not.
Create a recursive function that takes an integer n.
Check the base case, if the value of n is 0 then return -1.
Call the recursive function and get the ID of the potential celebrity from the first n-1 elements.
If the id is -1 then assign n as the potential celebrity and return the value.
If the potential  celebrity of first n-1 elements knows n-1 then return n-1, (0 based indexing)
If the celebrity of first n-1 elements does not know n-1 then return id of celebrity of n-1 elements, (0 based indexing)
Else return -1
Create a wrapper function and check whether the id returned by the function is really the celebrity or not.
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find celebrity#include <bits/stdc++.h>#include <list>using namespace std; // Max # of persons in the party#define N 8 // Person with 2 is celebritybool MATRIX[N][N] = { { 0, 0, 1, 0 },                      { 0, 0, 1, 0 },                      { 0, 0, 0, 0 },                      { 0, 0, 1, 0 } }; bool knows(int a, int b) { return MATRIX[a][b]; } // Returns -1 if a 'potential celebrity'// is not present. If present,// returns id (value from 0 to n-1).int findPotentialCelebrity(int n){    // base case - when n reaches 0 , returns -1    // since n represents the number of people,    // 0 people implies no celebrity(= -1)    if (n == 0)        return -1;     // find the celebrity with n-1    // persons    int id = findPotentialCelebrity(n - 1);     // if there are no celebrities    if (id == -1)        return n - 1;     // if the id knows the nth person    // then the id cannot be a celebrity, but nth person    // could be one    else if (knows(id, n - 1)) {        return n - 1;    }    // if the nth person knows the id,    // then the nth person cannot be a celebrity and the id    // could be one    else if (knows(n - 1, id)) {        return id;    }     // if there is no celebrity    return -1;} // Returns -1 if celebrity// is not present. If present,// returns id (value from 0 to n-1).// a wrapper over findCelebrityint Celebrity(int n){    // find the celebrity    int id = findPotentialCelebrity(n);     // check if the celebrity found    // is really the celebrity    if (id == -1)        return id;    else {        int c1 = 0, c2 = 0;         // check the id is really the        // celebrity        for (int i = 0; i < n; i++)            if (i != id) {                c1 += knows(id, i);                c2 += knows(i, id);            }         // if the person is known to        // everyone.        if (c1 == 0 && c2 == n - 1)            return id;         return -1;    }} // Driver codeint main(){    int n = 4;    int id = Celebrity(n);    id == -1 ? cout << "No celebrity"             : cout << "Celebrity ID " << id;    return 0;}
// Java program for the above approachimport java.io.*; class GFG{       // Max # of persons in the party    static int N = 8;     // Person with 2 is celebrity    static int MATRIX[][] = { { 0, 0, 1, 0 },                              { 0, 0, 1, 0 },                              { 0, 0, 0, 0 },                              { 0, 0, 1, 0 } };     static int knows(int a, int b) { return MATRIX[a][b]; }     // Returns -1 if a 'potential celebrity'    // is not present. If present,    // returns id (value from 0 to n-1).    static int findPotentialCelebrity(int n)    {        // base case - when n reaches 0 , returns -1        // since n represents the number of people,        // 0 people implies no celebrity(= -1)        if (n == 0)            return -1;         // find the celebrity with n-1        // persons        int id = findPotentialCelebrity(n - 1);         // if there are no celebrities        if (id == -1)            return n - 1;         // if the id knows the nth person        // then the id cannot be a celebrity, but nth person        // could be one        else if (knows(id, n - 1) == 1) {            return n - 1;        }        // if the nth person knows the id,        // then the nth person cannot be a celebrity and the        // id could be one        else if (knows(n - 1, id) == 1) {            return id;        }         // if there is no celebrity        return -1;    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    // a wrapper over findCelebrity    static int Celebrity(int n)    {        // find the celebrity        int id = findPotentialCelebrity(n);         // check if the celebrity found        // is really the celebrity        if (id == -1)            return id;        else {            int c1 = 0, c2 = 0;             // check the id is really the            // celebrity            for (int i = 0; i < n; i++)                if (i != id) {                    c1 += knows(id, i);                    c2 += knows(i, id);                }             // if the person is known to            // everyone.            if (c1 == 0 && c2 == n - 1)                return id;             return -1;        }    }     // Driver code    public static void main(String[] args)    {        int n = 4;        int id = Celebrity(n);        if (id == -1) {            System.out.println("No celebrity");        }        else {            System.out.println("Celebrity ID " + id);        }    }} // This code is contributed by Potta Lokesh
# Python3 program to find celebrity # Max # of persons in the partyN = 8 # Person with 2 is celebrityMATRIX = [[0, 0, 1, 0],           [0, 0, 1, 0],           [0, 0, 0, 0],           [0, 0, 1, 0]]  def knows(a, b):     return MATRIX[a][b] # Returns -1 if a potential celebrity# is not present. If present,# returns id (value from 0 to n-1).  def findPotentialCelebrity(n):     # Base case    if (n == 0):        return 0;     # Find the celebrity with n-1    # persons    id_ = findPotentialCelebrity(n - 1)     # If there are no celebrities    if (id_ == -1):        return n - 1    # if the id knows the nth person    # then the id cannot be a celebrity, but nth person    # could be on    elif knows(id_, n - 1):          return n - 1    # if the id knows the nth person    # then the id cannot be a celebrity, but nth person    # could be one    elif knows(n - 1, id_):          return id_    # If there is no celebrity    return - 1 # Returns -1 if celebrity# is not present. If present,# returns id (value from 0 to n-1).# a wrapper over findCelebritydef Celebrity(n):     # Find the celebrity    id_=findPotentialCelebrity(n)     # Check if the celebrity found    # is really the celebrity    if (id_ == -1):        return id_    else:        c1=0        c2=0         # Check the id is really the        # celebrity        for i in range(n):            if (i != id_):                c1 += knows(id_, i)                c2 += knows(i, id_)         # If the person is known to        # everyone.        if (c1 == 0 and c2 == n - 1):            return id_         return -1 # Driver codeif __name__ == '__main__':     n=4    id_=Celebrity(n)     if id_ == -1:        print("No celebrity")    else:        print("Celebrity ID", id_) # This code is contributed by UnworthyProgrammer
// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{       // Max # of persons in the party    static int N = 8;     // Person with 2 is celebrity    static int [,]MATRIX = { { 0, 0, 1, 0 },                              { 0, 0, 1, 0 },                              { 0, 0, 0, 0 },                              { 0, 0, 1, 0 } };     static int knows(int a, int b) { return MATRIX[a,b]; }     // Returns -1 if a 'potential celebrity'    // is not present. If present,    // returns id (value from 0 to n-1).    static int findPotentialCelebrity(int n)    {               // base case - when n reaches 0 , returns -1        // since n represents the number of people,        // 0 people implies no celebrity(= -1)        if (n == 0)            return -1;         // find the celebrity with n-1        // persons        int id = findPotentialCelebrity(n - 1);         // if there are no celebrities        if (id == -1)            return n - 1;         // if the id knows the nth person        // then the id cannot be a celebrity, but nth person        // could be one        else if (knows(id, n - 1) == 1) {            return n - 1;        }               // if the nth person knows the id,        // then the nth person cannot be a celebrity and the        // id could be one        else if (knows(n - 1, id) == 1) {            return id;        }         // if there is no celebrity        return -1;    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    // a wrapper over findCelebrity    static int Celebrity(int n)    {               // find the celebrity        int id = findPotentialCelebrity(n);         // check if the celebrity found        // is really the celebrity        if (id == -1)            return id;        else {            int c1 = 0, c2 = 0;             // check the id is really the            // celebrity            for (int i = 0; i < n; i++)                if (i != id) {                    c1 += knows(id, i);                    c2 += knows(i, id);                }             // if the person is known to            // everyone.            if (c1 == 0 && c2 == n - 1)                return id;             return -1;        }    }     // Driver code    public static void Main(String[] args)    {        int n = 4;        int id = Celebrity(n);        if (id == -1) {            Console.WriteLine("No celebrity");        }        else {            Console.WriteLine("Celebrity ID " + id);        }    }} // This code is contributed by gauravrajput1
<script>// JavaScript program for the above approach// Max # of persons in the partyvar N = 8;     // Person with 2 is celebrity    var MATRIX = [ [ 0, 0, 1, 0 ],                              [ 0, 0, 1, 0 ],                              [ 0, 0, 0, 0 ],                              [ 0, 0, 1, 0 ] ];     function knows(a, b)    {        return MATRIX[a][b];             }     // Returns -1 if a 'potential celebrity'    // is not present. If present,    // returns id (value from 0 to n-1).    function findPotentialCelebrity(n)    {        // base case - when n reaches 0 , returns -1        // since n represents the number of people,        // 0 people implies no celebrity(= -1)        if (n == 0)            return -1;         // find the celebrity with n-1        // persons        var id = findPotentialCelebrity(n - 1);         // if there are no celebrities        if (id == -1)            return n - 1;         // if the id knows the nth person        // then the id cannot be a celebrity, but nth person        // could be one        else if (knows(id, n - 1) == 1) {            return n - 1;        }        // if the nth person knows the id,        // then the nth person cannot be a celebrity and the        // id could be one        else if (knows(n - 1, id) == 1) {            return id;        }         // if there is no celebrity        return -1;    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    // a wrapper over findCelebrity    function Celebrity(n)    {        // find the celebrity        var id = findPotentialCelebrity(n);         // check if the celebrity found        // is really the celebrity        if (id == -1)            return id;        else {            var c1 = 0, c2 = 0;             // check the id is really the            // celebrity            for (var i = 0; i < n; i++)                if (i != id) {                    c1 += knows(id, i);                    c2 += knows(i, id);                }             // if the person is known to            // everyone.            if (c1 == 0 && c2 == n - 1)                return id;             return -1;        }    }     // Driver code        var n = 4;        var id = Celebrity(n);        if (id == -1) {            document.write("No celebrity");        }        else {            document.write("Celebrity ID " + id);        }     // This code is contributed by shivanisinghss2110</script>
Output :
Celebrity ID 2
Complexity Analysis: 
Time Complexity: O(n). The recursive function is called n times, so the time complexity is O(n).
Space Complexity: O(1). As no extra space is required.
Approach: There are some observations based on elimination technique (Refer Polya’s How to Solve It book). 
If A knows B, then A can’t be a celebrity. Discard A, and B may be celebrity.
If A doesn’t know B, then B can’t be a celebrity. Discard B, and A may be celebrity.
Repeat above two steps till there is only one person.
Ensure the remained person is a celebrity. (What is the need of this step?)
Algorithm: 
Create a stack and push all the id’s in the stack.Run a loop while there are more than 1 element in the stack.Pop top two element from the stack (represent them as A and B)If A knows B, then A can’t be a celebrity and push B in stack. Else if A doesn’t know B, then B can’t be a celebrity push A in stack.Assign the remaining element in the stack as the celebrity.Run a loop from 0 to n-1 and find the count of persons who knows the celebrity and the number of people whom the celebrity knows. if the count of persons who knows the celebrity is n-1 and the count of people whom the celebrity knows is 0 then return the id of celebrity else return -1.
Create a stack and push all the id’s in the stack.
Run a loop while there are more than 1 element in the stack.
Pop top two element from the stack (represent them as A and B)
If A knows B, then A can’t be a celebrity and push B in stack. Else if A doesn’t know B, then B can’t be a celebrity push A in stack.
Assign the remaining element in the stack as the celebrity.
Run a loop from 0 to n-1 and find the count of persons who knows the celebrity and the number of people whom the celebrity knows. if the count of persons who knows the celebrity is n-1 and the count of people whom the celebrity knows is 0 then return the id of celebrity else return -1.
Implementation: 
C++
Java
Python3
C#
Javascript
// C++ program to find celebrity#include <bits/stdc++.h>#include <list>using namespace std; // Max # of persons in the party#define N 8 // Person with 2 is celebritybool MATRIX[N][N] = {{0, 0, 1, 0},                    {0, 0, 1, 0},                    {0, 0, 0, 0},                    {0, 0, 1, 0}}; bool knows(int a, int b){    return MATRIX[a][b];} // Returns -1 if celebrity// is not present. If present,// returns id (value from 0 to n-1).int findCelebrity(int n){         stack<int> s;     // Celebrity    int C;     // Push everybody to stack    for (int i = 0; i < n; i++)        s.push(i);     // Extract top 2       // Find a potential celebrity    while (s.size() > 1)    {   int A = s.top();        s.pop();        int B = s.top();        s.pop();        if (knows(A, B))        {          s.push(B);        }        else        {          s.push(A);        }    }             // Potential candidate?    C = s.top();    s.pop();     // Check if C is actually    // a celebrity or not    for (int i = 0; i < n; i++)    {        // If any person doesn't        // know 'C' or 'C' doesn't        // know any person, return -1        if ( (i != C) &&                (knows(C, i) ||                 !knows(i, C)) )            return -1;    }     return C;} // Driver codeint main(){    int n = 4;    int id = findCelebrity(n);    id == -1 ? cout << "No celebrity" :               cout << "Celebrity ID " << id;    return 0;}
// Java program to find celebrity using// stack data structureimport java.util.Stack; class GFG{    // Person with 2 is celebrity    static int MATRIX[][] = { { 0, 0, 1, 0 },                            { 0, 0, 1, 0 },                            { 0, 0, 0, 0 },                            { 0, 0, 1, 0 } };     // Returns true if a knows    // b, false otherwise    static boolean knows(int a, int b)    {        boolean res = (MATRIX[a][b] == 1) ?                                     true :                                     false;        return res;    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    static int findCelebrity(int n)    {        Stack<Integer> st = new Stack<>();        int c;         // Step 1 :Push everybody        // onto stack        for (int i = 0; i < n; i++)        {            st.push(i);        }         while (st.size() > 1)        {            // Step 2 :Pop off top            // two persons from the            // stack, discard one            // person based on return            // status of knows(A, B).            int a = st.pop();            int b = st.pop();             // Step 3 : Push the            // remained person onto stack.            if (knows(a, b))            {                st.push(b);            }             else                st.push(a);        }               // If there are only two people        // and there is no        // potential candidate        if(st.empty())            return -1;         c = st.pop();         // Step 5 : Check if the last        // person is celebrity or not        for (int i = 0; i < n; i++)        {            // If any person doesn't            //  know 'c' or 'a' doesn't            // know any person, return -1            if (i != c && (knows(c, i) ||                          !knows(i, c)))                return -1;        }        return c;    }     // Driver Code    public static void main(String[] args)    {        int n = 4;        int result = findCelebrity(n);        if (result == -1)        {            System.out.println("No Celebrity");        }        else            System.out.println("Celebrity ID " +                                        result);    }} // This code is contributed// by Rishabh Mahrsee
# Python3 program to find celebrity# using stack data structure # Max # of persons in the partyN = 8 # Person with 2 is celebrityMATRIX = [ [ 0, 0, 1, 0 ],           [ 0, 0, 1, 0 ],           [ 0, 0, 0, 0 ],           [ 0, 0, 1, 0 ] ] def knows(a, b):         return MATRIX[a][b] # Returns -1 if celebrity# is not present. If present,# returns id (value from 0 to n-1).def findCelebrity(n):         # Handle trivial    # case of size = 2    s = []     # Push everybody to stack    for i in range(n):        s.append(i)      # Find a potential celebrity    while (len(s) > 1):                 # Pop out the first two elements from stack        A = s.pop()        B = s.pop()                 # if A knows B, we find that B might be the celebrity and vice versa        if (knows(A, B)):            s.append(B)        else:            s.append(A)                 # If there are only two people    # and there is no    # potential candidate    if(len(s) == 0):        return -1             # Potential candidate?    C = s.pop();     # Last candidate was not    # examined, it leads one    # excess comparison (optimize)    if (knows(C, B)):        C = B             if (knows(C, A)):        C = A     # Check if C is actually    # a celebrity or not    for i in range(n):             # If any person doesn't        # know 'a' or 'a' doesn't        # know any person, return -1        if ((i != C) and           (knows(C, i) or           not(knows(i, C)))):            return -1     return C     # Driver codeif __name__ == '__main__':         n = 4    id_ = findCelebrity(n)         if id_ == -1:        print("No celebrity")    else:      print("Celebrity ID ", id_) # This code is contributed by UnworthyProgrammer
// C# program to find celebrity using// stack data structureusing System;using System.Collections.Generic; public class GFG{    // Person with 2 is celebrity    static int [,]MATRIX = { { 0, 0, 1, 0 },                            { 0, 0, 1, 0 },                            { 0, 0, 0, 0 },                            { 0, 0, 1, 0 } };     // Returns true if a knows    // b, false otherwise    static bool knows(int a, int b)    {        bool res = (MATRIX[a,b] == 1) ?                                     true :                                     false;        return res;    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    static int findCelebrity(int n)    {        Stack<int> st = new Stack<int>();        int c;         // Step 1 :Push everybody        // onto stack        for (int i = 0; i < n; i++)        {            st.Push(i);        }         while (st.Count > 1)        {            // Step 2 :Pop off top            // two persons from the            // stack, discard one            // person based on return            // status of knows(A, B).            int a = st.Pop();            int b = st.Pop();             // Step 3 : Push the            // remained person onto stack.            if (knows(a, b))            {                st.Push(b);            }             else                st.Push(a);        }               // If there are only two people        // and there is no        // potential candidate        if(st.Count==0)            return -1;         c = st.Pop();         // Step 5 : Check if the last        // person is celebrity or not        for (int i = 0; i < n; i++)        {            // If any person doesn't            //  know 'c' or 'a' doesn't            // know any person, return -1            if (i != c && (knows(c, i) ||                          !knows(i, c)))                return -1;        }        return c;    }     // Driver Code    public static void Main(String[] args)    {        int n = 4;        int result = findCelebrity(n);        if (result == -1)        {            Console.WriteLine("No Celebrity");        }        else            Console.WriteLine("Celebrity ID " +                                        result);    }} // This code is contributed by umadevi9616
<script>// javascript program to find celebrity using// stack data structure    // Person with 2 is celebrity    var MATRIX = [ [ 0, 0, 1, 0 ],    [ 0, 0, 1, 0 ],    [ 0, 0, 0, 0 ],    [ 0, 0, 1, 0 ] ];     // Returns true if a knows    // b, false otherwise    function knows(a , b) {        var res = (MATRIX[a][b] == 1) ? true : false;        return res;    }     // Returns -1 if celebrity    // is not present. If present,    // returns id (value from 0 to n-1).    function findCelebrity(n) {        var st = new Array();        var c;         // Step 1 :Push everybody        // onto stack        for (var i = 0; i < n; i++) {            st.push(i);        }         while (st.length > 1)        {                     // Step 2 :Pop off top            // two persons from the            // stack, discard one            // person based on return            // status of knows(A, B).            var a = st.pop();            var b = st.pop();             // Step 3 : Push the            // remained person onto stack.            if (knows(a, b)) {                st.push(b);            }             else                st.push(a);        }         // If there are only two people        // and there is no        // potential candidate        if (st.length==0)            return -1;         c = st.pop();         // Step 5 : Check if the last        // person is celebrity or not        for (i = 0; i < n; i++)        {                     // If any person doesn't            // know 'c' or 'a' doesn't            // know any person, return -1            if (i != c && (knows(c, i) || !knows(i, c)))                return -1;        }        return c;    }     // Driver Code           var n = 4;        var result = findCelebrity(n);        if (result == -1) {            document.write("No Celebrity");        } else            document.write("Celebrity ID " + result); // This code is contributed by gauravrajput1</script>
Output : 
Celebrity ID 2
Complexity Analysis: 
Time Complexity: O(n). The total number of comparisons 3(N-1), so the time complexity is O(n).
Space Complexity: O(n). n extra space is needed to store the stack.
Optimal Approach: The idea is to use two pointers, one from start and one from the end. Assume the start person is A, and the end person is B. If A knows B, then A must not be the celebrity. Else, B must not be the celebrity. At the end of the loop, only one index will be left as a celebrity. Go through each person again and check whether this is the celebrity. The Two Pointer approach can be used where two pointers can be assigned, one at the start and the other at the end, and the elements can be compared and the search space can be reduced.  
Algorithm : 
Create two indices i and j, where i = 0 and j = n-1Run a loop until i is less than j.Check if i knows j, then i can’t be a celebrity. so increment i, i.e. i++Else j cannot be a celebrity, so decrement j, i.e. j–Assign i as the celebrity candidateNow at last check that whether the candidate is actually a celebrity by re-running a loop from 0 to n-1  and constantly checking that if the candidate knows a person or if there is a candidate who does not know the candidate, then we should return -1. else at the end of the loop, we can be sure that the candidate is actually a celebrity.
Create two indices i and j, where i = 0 and j = n-1
Run a loop until i is less than j.
Check if i knows j, then i can’t be a celebrity. so increment i, i.e. i++
Else j cannot be a celebrity, so decrement j, i.e. j–
Assign i as the celebrity candidate
Now at last check that whether the candidate is actually a celebrity by re-running a loop from 0 to n-1  and constantly checking that if the candidate knows a person or if there is a candidate who does not know the candidate, then we should return -1. else at the end of the loop, we can be sure that the candidate is actually a celebrity.
Implementation:
Java
Python3
C#
Javascript
C++
// Java program to find celebrity// in the given Matrix of people// Code by Sparsh_cbs import java.io.*; class GFG {    public static void main(String[] args)    {        int[][] M = { { 0, 0, 1, 0 },                      { 0, 0, 1, 0 },                      { 0, 0, 0, 0 },                      { 0, 0, 1, 0 } };         int celebIdx = celebrity(M, 4);         if (celebIdx == -1)            System.out.println("No celebrity found!");        else {            System.out.println(                "0-based celebrity index is : " + celebIdx);        }    }    public static int celebrity(int M[][], int n)    {        // This function returns the celebrity        // index 0-based (if any)         int i = 0, j = n - 1;        while (i < j) {            if (M[j][i] == 1) // j knows i                j--;            else // j doesnt know i so i cant be celebrity                i++;        }        // i points to our celebrity candidate        int candidate = i;         // Now, all that is left is to check that whether        // the candidate is actually a celebrity i.e: he is        // known by everyone but he knows no one        for (i = 0; i < n; i++) {            if (i != candidate) {                if (M[i][candidate] == 0                    || M[candidate][i] == 1)                    return -1;            }        }        // if we reach here this means that the candidate        // is really a celebrity        return candidate;    }}
# Python3 codeclass Solution:     # Function to find if there is a celebrity in the party or not.    # return index if celebrity else return -1    def celebrity(self, M, n):        # code here        i = 0        j = n-1        candidate = -1        while(i < j):            if M[j][i] == 1:                j -= 1            else:                i += 1         candidate = i        for k in range(n):            if candidate != k:                if M[candidate][k] == 1 or M[k][candidate] == 0:                    return -1         return candidate  n = 4m = [[0, 0, 1, 0],     [0, 0, 1, 0],     [0, 0, 0, 0],     [0, 0, 1, 0]]ob = Solution()print("Celebrity at index "+str(ob.celebrity(m, n)))
// C# program to find celebrity// in the given Matrix of people// Code by Sparsh_cbsusing System; class GFG {    public static void Main(String[] args)    {        int[,] M = { { 0, 0, 1, 0 },                      { 0, 0, 1, 0 },                      { 0, 0, 0, 0 },                      { 0, 0, 1, 0 } };         int celebIdx = celebrity(M, 4);         if (celebIdx == -1)            Console.Write("No celebrity found!");        else {            Console.Write(                "0-based celebrity index is : " + celebIdx);        }    }    public static int celebrity(int [,]M, int n)    {        // This function returns the celebrity        // index 0-based (if any)         int i = 0, j = n - 1;        while (i < j) {            if (M[j,i] == 1) // j knows i                j--;            else // i knows j                i++;        }               // i points to our celebrity candidate        int candidate = i;         // Now, all that is left is to check that whether        // the candidate is actually a celebrity i.e: he is        // known by everyone but he knows no one        for (i = 0; i < n; i++) {            if (i != candidate) {                if (M[i,candidate] == 0                    || M[candidate,i] == 1)                    return -1;            }        }               // if we reach here this means that the candidate        // is really a celebrity        return candidate;    }} // This code is contributed by shivanisinghss2110
<script>// JavaScript program to find celebrity// in the given Matrix of people// Code by Sparsh_cbsvar M = [ [ 0, 0, 1, 0 ],                      [ 0, 0, 1, 0 ],                      [ 0, 0, 0, 0 ],                      [ 0, 0, 1, 0 ] ];         var celebIdx = celebrity(M, 4);         if (celebIdx == -1)            document.write("No celebrity found!");        else {            document.write(                "0-based celebrity index is : " + celebIdx);        }     function celebrity( M, n)    {             // This function returns the celebrity        // index 0-based (if any)        var i = 0, j = n - 1;        while (i < j) {            if (M[j][i] == 1) // j knows i                j--;            else // i knows j                i++;        }                 // i points to our celebrity candidate        var candidate = i;         // Now, all that is left is to check that whether        // the candidate is actually a celebrity i.e: he is        // known by everyone but he knows no one        for (i = 0; i < n; i++) {            if (i != candidate) {                if (M[i][candidate] == 0                    || M[candidate][i] == 1)                    return -1;            }        }                 // if we reach here this means that the candidate        // is really a celebrity        return candidate;  }     // This code is contributed by shivanisinghss2110</script>
// C++ program to find celebrity// in the given Matrix of people#include<bits/stdc++.h>using namespace std;#define N 4  int celebrity(int M[N][N], int n)    {        // This function returns the celebrity        // index 0-based (if any)         int i = 0, j = n - 1;        while (i < j) {            if (M[j][i] == 1) // j knows i                j--;            else // j doesnt know i so i cant be celebrity                i++;        }        // i points to our celebrity candidate        int candidate = i;         // Now, all that is left is to check that whether        // the candidate is actually a celebrity i.e: he is        // known by everyone but he knows no one        for (i = 0; i < n; i++) {            if (i != candidate) {                if (M[i][candidate] == 0                    || M[candidate][i] == 1)                    return -1;            }        }        // if we reach here this means that the candidate        // is really a celebrity        return candidate;     }  int main()    {        int M[N][N] = { { 0, 0, 1, 0 },                      { 0, 0, 1, 0 },                      { 0, 0, 0, 0 },                      { 0, 0, 1, 0 } };         int celebIdx = celebrity(M, 4);         if (celebIdx == -1)            cout<<("No celebrity found!");        else {            cout<<                "0-based celebrity index is : " << celebIdx;        }        return 0;    } // This code contributed by gauravrajput1
Output : 
0-based celebrity index is : 2
Complexity Analysis: 
Time Complexity: O(n)
Space Complexity: O(1) No extra space is required.
Write code to find the celebrity. Don’t use any data structures like graphs, stack, etc... you have access to N and HaveAcquaintance(int, int) only.Implement the algorithm using Queues. What is your observation? Compare your solution with Finding Maximum and Minimum in an array and Tournament Tree. What is the minimum number of comparisons do we need (optimal number of calls to HaveAcquaintance())?
Write code to find the celebrity. Don’t use any data structures like graphs, stack, etc... you have access to N and HaveAcquaintance(int, int) only.
Implement the algorithm using Queues. What is your observation? Compare your solution with Finding Maximum and Minimum in an array and Tournament Tree. What is the minimum number of comparisons do we need (optimal number of calls to HaveAcquaintance())?
vt_m
andrew1234
rohitkumar52
parthpatel16
UnworthyProgrammer
Sumit Dutta
Rajput-Ji
aashish1995
manasabhat1
namangoyal198
todaysgaurav
sparshsharma2510
sakshamagrawal703
lokeshpotta20
shivanisinghss2110
GauravRajput1
santy2001
umadevi9616
dqureshiumar
surinderdawra388
stryker27
Amazon
Fab.com
Flipkart
Google
Microsoft
United Health Group
Zoho
Matrix
Stack
Zoho
Flipkart
Amazon
Microsoft
Google
Fab.com
United Health Group
Stack
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Efficiently compute sums of diagonals of a matrix
Printing all solutions in N-Queen Problem
Python program to multiply two matrices
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Queue using Stacks