Graph Theory37 sections · 1633 units
Open in Course

Town Judge - Implementation

Writing the Code

Here is the solution:

function findJudge(n, trust):
    countOut = array of size n + 1, all 0
    countIn = array of size n + 1, all 0

    for (u, v) in trust:
        countOut[u] = countOut[u] + 1
        countIn[v] = countIn[v] + 1

    for i from 1 to n:
        if countOut[i] == 0 and countIn[i] == n - 1:
            return i

    return -1

This runs in O(n+t)O(n + t) time where tt is the length of the trust array, and uses O(n)O(n) space.