#997

Find the Town Judge

Easy
ArrayHash TableGraph TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a counting approach to track how many people trust each person and how many people each person trusts. This allows us to identify the judge efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two arrays: one to count how many people trust each person and another to count how many people each person trusts.
  2. 2Step 2: Iterate through the trust relationships and update the counts accordingly.
  3. 3Step 3: Check for the person who is trusted by n-1 people and trusts nobody.
solution.py10 lines
1def findJudge(n, trust):
2    trust_count = [0] * (n + 1)
3    trusted_by_count = [0] * (n + 1)
4    for a, b in trust:
5        trust_count[a] += 1
6        trusted_by_count[b] += 1
7    for i in range(1, n + 1):
8        if trust_count[i] == 0 and trusted_by_count[i] == n - 1:
9            return i
10    return -1

Complexity note: The time complexity is O(n) because we only iterate through the trust array once and then through the people once. The space complexity is O(n) due to the two arrays used to count trust relationships.

  • 1The town judge must be trusted by everyone else, which means their trust count must be n-1.
  • 2The town judge trusts nobody, which means their own trust count must be 0.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.