A town has n people, numbered 1 to n. One of them might be the town judge. The judge trusts nobody, and every other person trusts the judge. At most one person can fit both rules.
You get trust, a list of pairs [a, b] meaning person a trusts person b. Any pair not in the list means no trust. Return the judge's number, or −1 if nobody fits.
Example 1
Input: n = 4, trust = [[1, 3], [2, 3], [4, 3]] Output: 3 Why: 1, 2 and 4 all trust 3, and 3 trusts no one
2 more examples and the constraints
Example 2
Input: n = 3, trust = [[1, 2], [2, 3]] Output: -1 Why: only 2 trusts 3, and 2 trusts someone
Example 3
Input: n = 1, trust = [] Output: 1 Why: the only person trusts nobody, and nobody else exists
Constraints
- 1 ≤ n ≤ 1,000
- 0 ≤ length of trust ≤ 10,000
- Each pair is listed once, and nobody trusts themselves
- 1 ≤ a, b ≤ n
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check each personO(n·t)
- One score per personO(n + t)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 people and 10,000 pairs | Verdict |
|---|---|---|---|
| Check each person | O(n·t) | Mention it, then move on | |
| One score per person | O(n + t) | Best; every pair read once |
n = number of people, t = number of trust pairs.
Edge cases to test
- A town of one. n = 1 with no pairs: person 1 is the judge, since n − 1 = 0 people need to trust them.
- Two people, no pairs. Nobody is trusted by the other: −1.
- The candidate trusts back. Everyone trusts 3, but 3 trusts 2: the score is n − 2, so −1.
- One vote missing. If even one person does not trust the candidate, there is no judge.
Common mistakes
- Returning the most trusted person without checking that they trust nobody.
- Forgetting n = 1, where the lone person is the judge even with no pairs.
- Sizing the array n instead of n + 1 and going out of bounds for person n.
How to talk through it
- 1Clarify. Are people numbered from 1? Can pairs repeat or can someone trust themselves?
- 2Give the brute force. Test each person against the whole list; O(n·t).
- 3See the graph. Pairs are arrows. The judge has n − 1 arrows in and none out.
- 4Fold it into one score. In minus out; explain why only the judge can reach n − 1.
- 5Test out loud. Run n = 1, two people with no pairs, and a candidate who trusts back.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?