-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCelebrity-Problem.cpp
More file actions
67 lines (60 loc) · 1.93 KB
/
Copy pathCelebrity-Problem.cpp
File metadata and controls
67 lines (60 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// GFG: https://practice.geeksforgeeks.org/problems/the-celebrity-problem/1
// Approach 1: brute force O(N^2)
class Solution
{
public:
//Function to find if there is a celebrity in the party or not.
int celebrity(vector<vector<int> >& M, int n)
{
for(int i=0; i<n; i++){
// check if everybody knows celebrity --> i (assume i is celebrity)
bool one = true;
for(int j=0; j<n; j++){
if(i == j) continue;
if(M[j][i]!=1){
one = false;
break;
}
}
// check if celebrity (i) does not know everybody
bool two = true;
for(int j=0; j<n; j++){
if(i==j) continue;
if(M[i][j]!=0){
two = false;
break;
}
}
if(one && two) return i;
}
return -1;
}
};
// Approach 2: brute force O(N)
class Solution
{
public:
//Function to find if there is a celebrity in the party or not.
int celebrity(vector<vector<int> >& M, int n)
{
stack<int> st;
for(int i=0; i<n; i++) st.push(i);
while(st.size() > 1){
int first = st.top(); st.pop();
int second = st.top(); st.pop();
if(M[first][second] && M[second][first]) continue;
else if(M[first][second] && !M[second][first]) st.push(second);
else if(!M[first][second] && M[second][first]) st.push(first);
}
if(st.empty()) return -1;
int candidate = st.top();
for(int i=0; i<n; i++){
if(i==candidate) continue;
// check if everybody knows candidate
if(!M[i][candidate]) return -1;
// check if candidate knows anyone
if(M[candidate][i]) return -1;
}
return candidate;
}
};