Challenge: Solve a Celebrity Problem Using a Stack
Can you solve this celebrity problem using a built-in Stack? A solution is placed in the "solution" section to help you, but we would suggest you try to solve it on your own first.
We'll cover the following
Problem Statement #
In this problem, you have to implement findCelebrity()
method to find the celebrity in a party (matrix) using a stack. A celebrity is someone that everyone knows, but he/she doesn’t know anyone at the party.
Method Prototype: #
int findCelebrity(int[][] party,int numPeople);
Where the party is a reference variable storing a 2D matrix, which has stored all the information about acquaintances, numPeople and the number of people present in the party.
In the party matrix, a particular [row][col] stores acquaintance information for row and col. In other words, if [row][col] == 1, then it means row knows col, and if it’s zero, then it means row doesn’t know col. Remember that everyone knows a celebrity, but the celebrity doesn’t know the people at the party.
An illustration is also provided for your understanding.
Output: #
It will return - 1 if there is no celebrity in the party. Otherwise, it will return the ID or number of celebrities from the party matrix.
Sample Input #
party = {
{0,1,1,0},
{1,0,1,1},
{0,0,0,0},
{0,1,1,0},
}
numPeople = 4 (Number of rows in party array)
Sample Output #
2 (because row Index = 2 is a celebrity)
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.