Leetcode 997: Find the Town Judge

grid47
grid47
Exploring patterns and algorithms
Jul 30, 2024 5 min read

In a town with n people, one person may be the judge. The judge trusts no one and is trusted by everyone else. Given a list of trust relationships, identify the town judge or return -1 if no judge exists.
Problem
Approach
Steps
Complexity
Input: The input consists of a number n (the total number of people) and an array trust where trust[i] = [a, b] means that person a trusts person b.
Example: n = 2, trust = [[1, 2]]
Constraints:
• 1 <= n <= 1000
• 0 <= trust.length <= 104
• trust[i].length == 2
• ai != bi
• 1 <= ai, bi <= n
Output: Return the label of the town judge if one exists, or return -1 if no judge can be identified.
Example: Output: 2
Constraints:
• The label of the town judge should be between 1 and n, inclusive.
Goal: Identify the person who satisfies the judge's conditions of being trusted by everyone and trusting no one.
Steps:
• Step 1: Create an array to track the trust levels of each person.
• Step 2: Update the trust levels based on the trust relationships.
• Step 3: Identify the person who has trust level n-1 (trusted by everyone else and trusts no one).
• Step 4: Return the person if found, or -1 if no such person exists.
Goal: The input must conform to the given constraints for the problem to be solvable.
Steps:
• 1 <= n <= 1000
• 0 <= trust.length <= 104
• Each pair in the trust array is unique.
• 1 <= ai, bi <= n
Assumptions:
• The grid of trust relationships is sparse and doesn't contain redundant pairs.
Input: n = 2, trust = [[1, 2]]
Explanation: Person 2 is the town judge because they are trusted by person 1 and trust no one else.

Input: n = 3, trust = [[1, 3], [2, 3]]
Explanation: Person 3 is trusted by both person 1 and person 2, and trusts no one else, making them the town judge.

Input: n = 3, trust = [[1, 3], [2, 3], [3, 1]]
Explanation: Person 3 cannot be the judge because they trust person 1, violating the condition that the judge trusts no one.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus