Skip to content

Commit fe61792

Browse files
Create Day 10 Find the Town Judge.cpp
1 parent b206168 commit fe61792

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

Day 10 Find the Town Judge.cpp

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
PROBLEM:
2+
3+
4+
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
5+
6+
If the town judge exists, then:
7+
8+
The town judge trusts nobody.
9+
Everybody (except for the town judge) trusts the town judge.
10+
There is exactly one person that satisfies properties 1 and 2.
11+
You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.
12+
13+
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.
14+
15+
16+
17+
Example 1:
18+
19+
Input: N = 2, trust = [[1,2]]
20+
Output: 2
21+
Example 2:
22+
23+
Input: N = 3, trust = [[1,3],[2,3]]
24+
Output: 3
25+
Example 3:
26+
27+
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
28+
Output: -1
29+
Example 4:
30+
31+
Input: N = 3, trust = [[1,2],[2,3]]
32+
Output: -1
33+
Example 5:
34+
35+
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
36+
Output: 3
37+
38+
39+
40+
SOLUTION:
41+
42+
class Solution {
43+
public:
44+
int findJudge(int N, vector<vector<int>>& trust) {
45+
46+
unordered_map<int,int> m;
47+
int i,j,n,ans=-1,k;
48+
n=trust.size();
49+
50+
for(i=0;i<n;i++)
51+
{
52+
m[trust[i][1]]++;
53+
}
54+
55+
for(i=1;i<=N;i++)
56+
{
57+
if(m[i]==N-1 && ans==-1)
58+
{
59+
ans=i;
60+
break;
61+
}
62+
63+
}
64+
65+
if(ans!=-1)
66+
{
67+
for(i=0;i<n;i++)
68+
{
69+
if(trust[i][0]==ans)
70+
{
71+
ans=-1;
72+
break;
73+
}
74+
}
75+
}
76+
77+
return ans;
78+
}
79+
};

0 commit comments

Comments
 (0)