progress

~/problems / Graphs / DFS and connected components

Find the Town Judge

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~12 min

A village has people 1 to n. A survey collected pairs [a, b] meaning "a trusts b". There may be one referee: someone who trusts nobody while everyone else trusts them.

Implement find_trusted(n: int, trust: list[list[int]]) -> int: the referee's label, or -1 if nobody fits.

find_trusted(3, [[1, 3], [2, 3]])              # 3
find_trusted(3, [[1, 3], [2, 3], [3, 1]])      # -1   (3 trusts someone)
find_trusted(4, [[1, 2], [3, 2], [1, 3]])      # -1   (4 doesn't trust 2)
find_trusted(1, [])                            # 1    (alone, trusting nobody)

Up to 100,000 people and 200,000 distinct pairs; nobody trusts themselves. ⭐ Bonus: a speed test with 100,000 people earns a star in O(n + number of pairs).

Show hint

Two numbers per person settle it: how many trust them, and how many they trust.

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc