Find the Town Judge — LeetCode 997 Python Solution

EasyGraphArrayHash Table
Problem
#997
Reading time
2 min

The problem

In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.

Example

Input
n = 2, trust = [[1,2]]
Output
2

Python solution

Python
class Solution:
    def findJudge(self, n: int, trust: List[List[int]]) -> int:
        cnt1 = [0] * (n + 1)
        cnt2 = [0] * (n + 1)
        for a, b in trust:
            cnt1[a] += 1
            cnt2[b] += 1
        for i in range(1, n + 1):
            if cnt1[i] == 0 and cnt2[i] == n - 1:
                return i
        return -1

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Depth-First Search

Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 997. Find the Town Judge is filed here because LeetCode tags it Graph, which is the vocabulary this hub collects.

The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 997. Find the Town Judge?
LeetCode 997. Find the Town Judge is rated Easy on LeetCode.
What is the time complexity of LeetCode 997. Find the Town Judge?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 997. Find the Town Judge?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 997. Find the Town Judge cover?
LeetCode 997. Find the Town Judge is tagged Graph, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview