Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none).

Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none).
def judge(n, trust):
    score = [0] * (n + 1)
    for a, b in trust:
        score[a] -= 1; score[b] += 1
    for i in range(1, n + 1):
        if score[i] == n - 1: return i
    return -1
print(judge(3, [[1, 3], [2, 3]]), judge(3, [[1, 3], [2, 3], [3, 1]]), judge(1, []))
What is printed?
  1. A. 3 3 1
  2. B. 3 -1 -1
  3. C. 3 -1 1
  4. D. -1 -1 1

Correct answer: C. 3 -1 1

Score = in-degree − out-degree. The judge has in-degree n − 1 and out-degree 0, so score n − 1, and nobody else can reach it. In the second case 3 trusts 1, so its score is 1. With one person and no trust, that person is the judge (n − 1 = 0). O(n + E).

More Coding Interview Problems questions

Exams that ask this topic