AFFILIATE LINKS
Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard
/**
* @param {number} N
* @param {number[][]} trust
* @return {number}
*/
let findJudge = function(N, trust) {
// store the trust counts in an array. initialize all counts at zero
// the array has a length of one more than the population for convenience (person 1's count is index 1 of the array. person 2's count is index 2 of the array, etc.)
// index zero is a dummy value of 0 and will never be changed
let trustCounts = new Array(N + 1).fill(0);
// loop over each trust pair in the array
for (let [i, j] of trust) {
trustCounts[i] -= 1; // the trusting person needs to be decremented by one
trustCounts[j] += 1; // the trusted person needs to be incremented by one
}
// loop over the trust counts
for (let i = 1; i < trustCounts.length; i++) {
// if there is a person with one less trust count than the population, that person is the judge
if (trustCounts[i] === N - 1) {
return i;
}
}
// return -1 if there is no judge
return -1;
};
Can you provide this solution using C?