The Celebrity Problem
Last Updated :
29 Jul, 2024
Given a square matrix M[][] of size N X N, such that M[i][j] = 1 means ith person knows jth person, the task is to find the celebrity. A celebrity is a person who is known to all but does not know anyone. Return the index of the celebrity, if there is no celebrity return -1.
Note: Follow 0 based indexing and M[i][i] will always be 0.
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.
[Naive Approach] – Using Adjacency List – O(N^2) Time and O(N) Space
Analyze the problem 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 node in the graph which has the outdegree as zero and indegree equals to N-1.
Follow the steps below to solve the problem:
- 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.
Below is the implementation of the above approach:
C++
// C++ program to find celebrity
#include <bits/stdc++.h>
using namespace std;
bool knows(int a, int b, vector<vector<int> >& matrix)
{
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, vector<vector<int> >& matrix)
{
// 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, matrix);
// 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
int main()
{
int n = 4;
vector<vector<int> > matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int id = findCelebrity(n, matrix);
if (id == -1)
cout << "No celebrity";
else
cout << "Celebrity ID " << id;
return 0;
}
Java
// java program to find celebrity
import java.util.*;
public class GFG {
// Function to check if person 'a' knows person 'b'
static boolean knows(int a, int b, int[][] matrix)
{
return matrix[a][b] == 1;
}
// Returns -1 if celebrity is not present. If present,
// returns id (value from 0 to n-1).
static int findCelebrity(int n, int[][] matrix)
{
// 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++) {
// Convert boolean result to int (1 for
// true, 0 for false)
int x = knows(i, j, matrix) ? 1 : 0;
// 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;
}
public static void main(String[] args)
{
int n = 4;
int[][] matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int id = findCelebrity(n, matrix);
if (id == -1) {
System.out.println("No celebrity");
}
else {
System.out.println("Celebrity ID " + id);
}
}
}
Python
# python program to find celebrity
def knows(a, b, matrix):
return matrix[a][b]
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
def findCelebrity(n, matrix):
# the graph needs not be constructed
# as the edges can be found by
# using knows function
# degree array;
indegree = [0] * n
outdegree = [0] * n
# query for all edges
for i in range(n):
for j in range(n):
x = knows(i, j, matrix)
# 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
matrix = [ [0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0] ]
id = findCelebrity(n, matrix)
if id == -1:
print("No celebrity")
else:
print(f"Celebrity ID {id}")
C#
// C# program to find celebrity
using System;
class Program {
static bool Knows(int a, int b, int[, ] matrix)
{
return matrix[a, b] == 1;
}
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
static int FindCelebrity(int n, int[, ] matrix)
{
// 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++) {
bool x = Knows(i, j, matrix);
// set the degrees
if (x) {
outdegree[i]++;
indegree[j]++;
}
}
}
// 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
static void Main()
{
int n = 4;
int[, ] matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int id = FindCelebrity(n, matrix);
if (id == -1)
Console.WriteLine("No celebrity");
else
Console.WriteLine("Celebrity ID " + id);
}
}
JavaScript
// javascript program to find celebrity
function knows(a, b, matrix) { return matrix[a][b]; }
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
function findCelebrity(n, matrix)
{
// the graph needs not be constructed
// as the edges can be found by
// using knows function
// degree array;
let indegree = new Array(n).fill(0);
let outdegree = new Array(n).fill(0);
// query for all edges
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
let x = knows(i, j, matrix);
// set the degrees
outdegree[i] += x;
indegree[j] += x;
}
}
// find a person with indegree n-1
// and out degree 0
for (let i = 0; i < n; i++) {
if (indegree[i] === n - 1 && outdegree[i] === 0) {
return i;
}
}
return -1;
}
// Driver code
let n = 4;
let matrix = [
[ 0, 0, 1, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ],
[ 0, 0, 1, 0 ]
];
let id = findCelebrity(n, matrix);
if (id === -1) {
console.log("No celebrity");
}
else {
console.log("Celebrity ID " + id);
}
Time Complexity: O(N2), A nested loop is run traversing the array
Auxiliary Space: O(N), Since extra space of size N is required.
[Efficient Approach] Using Stack- O(N) Time and O(N) Space
Some observations are based on Stack Based elimination technique :
- 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.
Follow the steps below to solve the problem:
- Create a stack and push all the ids in the stack.
- Run a loop while there are more than 1 element in the stack.
- Pop the top two elements from the stack (represent them as A and B)
- If A knows B, then A can’t be a celebrity and push B in the stack. Else if A doesn’t know B, then B can’t be a celebrity push A in the 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 the celebrity else return -1.
Below is the implementation of the above approach:
C++
// C++ program to find celebrity using
// stack data structure
#include <bits/stdc++.h>
using namespace std;
// knows function check if a knows b
bool knows(int a, int b, vector<vector<int> >& matrix)
{
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, vector<vector<int> >& matrix)
{
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, matrix)) {
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, matrix)
|| !knows(i, C, matrix)))
return -1;
}
return C;
}
// Driver code
int main()
{
int n = 4;
vector<vector<int> > matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int id = findCelebrity(n, matrix);
if (id == -1)
cout << "No celebrity";
else
cout << "Celebrity ID " << id;
return 0;
}
Java
// java program to find celebrity using
// stack data structure
import java.util.Stack;
public class CelebrityFinder {
// knows function check if a knows b
static boolean knows(int a, int b, int[][] matrix)
{
return matrix[a][b] == 1;
}
// Returns -1 if celebrity is not present. If present,
// returns id (value from 0 to n-1).
static int findCelebrity(int n, int[][] matrix)
{
Stack<Integer> s = new Stack<>();
// 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.pop();
int B = s.pop();
if (knows(A, B, matrix)) {
s.push(B);
}
else {
s.push(A);
}
}
// Potential candidate?
C = 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, matrix)
|| !knows(i, C, matrix))) {
return -1;
}
}
return C;
}
public static void main(String[] args)
{
int n = 4;
int[][] matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int id = findCelebrity(n, matrix);
if (id == -1) {
System.out.println("No celebrity");
}
else {
System.out.println("Celebrity ID " + id);
}
}
}
Python
# python program to find celebrity using
# stack data structure
def knows(a, b, matrix):
return matrix[a][b] == 1
# Returns -1 if celebrity is not present. If present, returns id (value from 0 to n-1).
def findCelebrity(n, matrix):
stack = []
# Celebrity
C = -1
# Push everybody to stack
for i in range(n):
stack.append(i)
# Extract top 2
# Find a potential celebrity
while len(stack) > 1:
A = stack.pop()
B = stack.pop()
if knows(A, B, matrix):
stack.append(B)
else:
stack.append(A)
# Potential candidate?
C = stack.pop()
# Check if C is actually a celebrity or not
for i in range(n):
# If any person doesn't know 'C' or 'C' doesn't know any person, return -1
if i != C and (knows(C, i, matrix) or not knows(i, C, matrix)):
return -1
return C
def main():
n = 4
matrix = [
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]
]
id = findCelebrity(n, matrix)
if id == -1:
print("No celebrity")
else:
print(f"Celebrity ID {id}")
if __name__ == "__main__":
main()
C#
// C# program to find celebrity using
// stack data structure
using System;
using System.Collections.Generic;
class CelebrityFinder {
// Function to check if person 'a' knows person 'b'
static bool Knows(int a, int b, int[, ] matrix)
{
return matrix[a, b] == 1;
}
// Returns -1 if celebrity is not present. If present,
// returns id (value from 0 to n-1).
static int FindCelebrity(int n, int[, ] matrix)
{
Stack<int> stack = new Stack<int>();
// Celebrity
int C;
// Push everybody to stack
for (int i = 0; i < n; i++) {
stack.Push(i);
}
// Extract top 2
// Find a potential celebrity
while (stack.Count > 1) {
int A = stack.Pop();
int B = stack.Pop();
if (Knows(A, B, matrix)) {
stack.Push(B);
}
else {
stack.Push(A);
}
}
// Potential candidate?
C = stack.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, matrix)
|| !Knows(i, C, matrix))) {
return -1;
}
}
return C;
}
static void Main()
{
int n = 4;
int[, ] matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int id = FindCelebrity(n, matrix);
if (id == -1)
Console.WriteLine("No celebrity");
else
Console.WriteLine("Celebrity ID " + id);
}
}
JavaScript
// javascriptprogram to find celebrity using
// stack data structure
function knows(a, b, matrix) { return matrix[a][b] === 1; }
// Returns -1 if celebrity is not present. If present,
// returns id (value from 0 to n-1).
function findCelebrity(n, matrix)
{
let stack = [];
// Celebrity
let C;
// Push everybody to stack
for (let i = 0; i < n; i++) {
stack.push(i);
}
// Extract top 2
// Find a potential celebrity
while (stack.length > 1) {
let A = stack.pop();
let B = stack.pop();
if (knows(A, B, matrix)) {
stack.push(B);
}
else {
stack.push(A);
}
}
// Potential candidate?
C = stack.pop();
// Check if C is actually a celebrity or not
for (let 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, matrix)
|| !knows(i, C, matrix))) {
return -1;
}
}
return C;
}
// Driver code
function main()
{
let n = 4;
let matrix = [
[ 0, 0, 1, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ],
[ 0, 0, 1, 0 ]
];
let id = findCelebrity(n, matrix);
if (id === -1) {
console.log("No celebrity");
}
else {
console.log("Celebrity ID " + id);
}
}
main();
Time Complexity: O(N), where N is the number of persons.
Auxiliary Space: O(N) as we are using Stack.
[Expected Approach] Using Two Pointers – O(N) Time and O(1) Space
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.
Follow the steps below to solve the problem:
- 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 whether the candidate is actually a celebrity by re-running a loop from 0 to n-1 and constantly checking 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.
Below is the implementation of the above approach:
C++
// C++ program to find celebrity
// in the given Matrix using two-pointer approach
#include <bits/stdc++.h>
using namespace std;
int celebrity(vector<vector<int> >& matrix, int n)
{
// This function returns the celebrity
// index 0-based (if any)
int i = 0, j = n - 1;
while (i < j) {
if (matrix[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 (matrix[i][candidate] == 0
|| matrix[candidate][i] == 1)
return -1;
}
}
// if we reach here this means that the candidate
// is really a celebrity
return candidate;
}
int main()
{
int n = 4;
vector<vector<int> > matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int celebIdx = celebrity(matrix, n);
if (celebIdx == -1)
cout << ("No Celebrity");
else {
cout << "Celebrity ID " << celebIdx;
}
return 0;
}
Java
// java program to find celebrity
// in the given Matrix using two-pointer approach
import java.util.*;
public class GFG {
static int celebrity(int[][] matrix, int n) {
// This function returns the celebrity
// index 0-based (if any)
int i = 0, j = n - 1;
while (i < j) {
if (matrix[j][i] == 1) // j knows i
j--;
else // j doesn't know i so i can't 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 (matrix[i][candidate] == 0
|| matrix[candidate][i] == 1)
return -1;
}
}
// if we reach here this means that the candidate
// is really a celebrity
return candidate;
}
public static void main(String[] args) {
int n = 4;
int[][] matrix = {
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 }
};
int celebIdx = celebrity(matrix, n);
if (celebIdx == -1)
System.out.println("No Celebrity");
else {
System.out.println("Celebrity ID " + celebIdx);
}
}
}
Python
# python program to find celebrity
# in the given Matrix using two-pointer approach
def celebrity(matrix, n):
# This function returns the celebrity
# index 0-based (if any)
i, j = 0, n - 1
while i < j:
if matrix[j][i] == 1: # j knows i
j -= 1
else: # j doesn't know i so i can't be celebrity
i += 1
# i points to our celebrity candidate
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 in range(n):
if i != candidate:
if matrix[i][candidate] == 0 or matrix[candidate][i] == 1:
return -1
# if we reach here this means that the candidate
# is really a celebrity
return candidate
def main():
n = 4
matrix = [
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]
]
celeb_idx = celebrity(matrix, n)
if celeb_idx == -1:
print("No Celebrity")
else:
print(f"Celebrity ID {celeb_idx}")
if __name__ == "__main__":
main()
C#
// C# program to find celebrity
// in the given Matrix using two-pointer approach
using System;
class CelebrityFinder {
static int Celebrity(int[, ] matrix, int n)
{
// This function returns the celebrity
// index 0-based (if any)
int i = 0, j = n - 1;
while (i < j) {
if (matrix[j, i] == 1) // j knows i
j--;
else // j doesn't know i so i can't 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 (int k = 0; k < n; k++) {
if (k != candidate) {
if (matrix[k, candidate] == 0
|| matrix[candidate, k] == 1)
return -1;
}
}
// if we reach here this means that the candidate
// is really a celebrity
return candidate;
}
static void Main()
{
int n = 4;
int[, ] matrix = { { 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
int celebIdx = Celebrity(matrix, n);
if (celebIdx == -1)
Console.WriteLine("No Celebrity");
else
Console.WriteLine("Celebrity ID " + celebIdx);
}
}
JavaScript
// javascript program to find celebrity
// in the given Matrix using two - pointer approach
function celebrity(matrix, n)
{
// This function returns the celebrity
// index 0-based (if any)
let i = 0, j = n - 1;
while (i < j) {
if (matrix[j][i] === 1) { // j knows i
j--;
}
else { // j doesn't know i so i can't be celebrity
i++;
}
}
// i points to our celebrity candidate
let 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 (let k = 0; k < n; k++) {
if (k !== candidate) {
if (matrix[k][candidate] === 0
|| matrix[candidate][k] === 1) {
return -1;
}
}
}
// if we reach here this means that the candidate
// is really a celebrity
return candidate;
}
function main()
{
let n = 4;
let matrix = [
[ 0, 0, 1, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ],
[ 0, 0, 1, 0 ]
];
let celebIdx = celebrity(matrix, n);
if (celebIdx === -1)
console.log("No Celebrity");
else
console.log("Celebrity ID " + celebIdx);
}
main();
Time Complexity: O(N), Iterating two times the array of size N.
Auxiliary Space: O(1) No extra space is required.