Stacks and Queues · Coding problem
Find the Town Judge
A free coding problem from the Stack Elimination Search skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
People 1 to n live in a town, and a b means person a trusts person b. The town has a judge if exactly one person is trusted by everyone else and trusts no one. Return that person's number, or -1 if there's no judge.
Input format
n m
<a b> (m lines)
Example
Input:
4 4
1 4
2 4
3 4
1 2
Output: 4
Everyone else trusts person 4, who trusts no one; person 1 trusting person 2 as well doesn't change that. A town of one person, with no trust at all, has a judge: person 1.
Constraints
1 <= n <= 10000 <= m <= 10^4a != b, and each pair appears at most once
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Stack Elimination Search
Solve it Find the Town Judge free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime