Leetcode 997 - Find the Town Judge with Code
Grow Your Tech Career. Meet Expert coaches from top companies
Here is a step-by-step guide on how to solve the LeetCode problem #997: Find the Town Judge.
Understanding the Problem
In a town, there are N
people labelled from 1
to N
. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
- The town judge trusts nobody.
- Everybody (except for the town judge) trusts the town judge.
- There is exactly one person that satisfies properties 1 and 2.
You are given trust
, an array of pairs trust[i] = [a, b]
representing that the person labelled a
trusts the person labelled b
.
If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1
.
Plan your Solution
To solve this problem, we need to find the person who is trusted by everyone else, but trusts no one. Here is a plan to solve this problem:
- Create two lists,
in_degree
andout_degree
, of sizeN + 1
. These lists will store the in-degree (number of people trusting a person) and out-degree (number of people a person trusts) of each person. Initialize both lists with all zeros. - Iterate through the
trust
array and update the in-degree and out-degree of each person. For example, iftrust[i] = [a, b]
, we will incrementin_degree[b]
andout_degree[a]
. - Iterate through the
in_degree
andout_degree
lists. If a person hasin_degree[i] = N - 1
(everyone trusts them) andout_degree[i] = 0
(they trust no one), then they are the town judge. Return their labeli
. - If no such person is found, return
-1
.
Implement your Solution
Now that we have a plan, let’s implement the solution in Python:
def findJudge(N: int, trust: List[List[int]]) -> int:
# Create two lists to store the in-degree and out-degree of each person
in_degree = [0] * (N + 1)
out_degree = [0] * (N + 1)
# Update the in-degree and out-degree of each person
for a, b in trust:
in_degree[b] += 1
out_degree[a] += 1
# Find the person with in-degree N - 1 and out-degree 0
for i in range(1, N + 1):
if in_degree[i] == N - 1 and out_degree[i] == 0:
return i
# If no such person is found, return -1
return -1
This solution has a time complexity of O(N) and a space complexity of O(N).
Test your Solution
Here are some test cases that you can use to test the solution.
# Test case 1
# There are 2 people and person 1 trusts person 2
assert findJudge(2, [[1,2]]) == 2
# Test case 2
# There are 3 people and person 1 trusts person 3, person 2 trusts person 3
assert findJudge(3, [[1,3],[2,3]]) == 3
# Test case 3
# There are 3 people and person 1 trusts person 3, person 2 trusts person 3, person 3 trusts person 1
assert findJudge(3, [[1,3],[2,3],[3,1]]) == -1
# Test case 4
# There is only one person
assert findJudge(1, []) == 1
# Test case 5
# There are 2 people and no trusts are given
assert findJudge(2, []) == -1
I hope these test cases are helpful.
Grow Your Tech Career. Meet Expert coaches from top companies
Related: