


1. The helper function ‘knows’ is already implemented for you.
2. ‘knows(A, B)’ returns "false", if A doesn't know B.
3. You should not implement helper function ‘knows’, or speculate about its implementation.
4. You should minimize the number of calls to function ‘knows(A, B)’.
5. There are at least 2 people at the party.
6. At most one celebrity will exist.
The first line of input contains an integer ‘T’ denoting the number of test cases. The description of ‘T’ test cases follows.
The first line of each test case contains an integer ‘N’, representing the number of people in the party.
For each test case, print an integer representing the id of the celebrity. If there is no celebrity at the party then print -1.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
2 <= N <= 10^4
Where ‘T’ is the total number of test cases, ‘N’ is the number of people at the party.
Time Limit: 1sec
This problem can be modelled as a graph problem. Consider a directed graph having ‘N’ nodes numbered from 0 to ‘N’ - 1. If the helper function ‘knows(i, j)’ returns true, then it means that there is a directed edge from node ‘i’ to node ‘j’. We can observe that if the celebrity is present then it is represented by a global sink i.e node that has indegree n-1 and outdegree 0.
Algorithm is as follows:
Approach: If for any pair (i, j) such that ‘i’!= ‘j’, if ‘knows(i, j)’ returns true, then it implies that the person having id ‘i’ cannot be a celebrity as it knows the person having id ‘j’. Similarly if ‘knows(i, j)’ returns false, then it implies that the person having id ‘j’ cannot be a celebrity as it is not known by a person having id ‘i’. We can use this observation to solve this problem
Algorithm is as follows:
Approach: If for any pair ('i', ‘j’) such that 'i' != ‘j’, If ‘knows(i, j)’ returns true, then it implies that the person having id ‘i’ cannot be a celebrity as it knows the person having id ‘j’. Similarly if ‘knows(i, j)’ returns false, then it implies that the person having id ‘j’ cannot be a celebrity as it is not known by a person having id ‘i’.
So, the Two Pointer approach can be used where two pointers can be assigned, one at the start and the other at the end of the elements to be checked, and the search space can be reduced. This approach can be implemented as follow -:
Algorithm is as follows: