Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

997. Find the Town Judge

In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

You are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.

Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.

Most intuitive

Code

class Solution {
public:
    int findJudge(int n, vector<vector<int>>& t)
    {
        vector<int> trusts(n + 1, 0), trusted(n + 1, 0);
        for (int i = 0; i < t.size(); i++) { // here t.size() not n
            trusts[t[i][0]]++;
            trusted[t[i][1]]++;
        }
        for (int i = 1; i <= n; i++) {
            if (trusted[i] == n - 1 && trusts[i] == 0) {
                return i;
            }
        }
        return -1;
    }
};