Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Find the Town Judge

Easy · Graphs · Asked at Amazon, Microsoft, TCS, Infosys

A town has n people labelled 1 to n. A pair a b means person a trusts person b. The town judge, if one exists, trusts nobody and is trusted by everybody else. Print the judge’s label, or -1 if there is no judge.

Input

First line: n m. Next m lines: a b (all pairs distinct, a ≠ b).

Output

The label of the judge, or -1.

Constraints

Think of trust as a directed edge. The judge has in-degree n − 1 and out-degree 0. One pass over the pairs fills both degree arrays.

Example 1

Input

3 2
1 3
2 3

Output

3

Example 2

Input

3 3
1 3
2 3
3 1

Output

-1

Hints

  1. Treat "a trusts b" as a directed edge a → b.
  2. The judge has n − 1 incoming edges and no outgoing ones.
  3. One score per person: +1 for being trusted, −1 for trusting.

Approach

Keep score[i] = (times i is trusted) − (times i trusts). Only the judge can reach n − 1: being trusted by all n − 1 others gives n − 1, and trusting anyone would lower it. Scan for a person with that score. With n = 1 and no pairs, person 1 is the judge.

Complexity: O(n + m) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    vector<int> score(n + 1, 0);
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        score[a]--;
        score[b]++;
    }
    for (int i = 1; i <= n; i++)
        if (score[i] == n - 1) {
            cout << i << "\n";
            return 0;
        }
    cout << -1 << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n, m = data[0], data[1]
score = [0] * (n + 1)
for i in range(m):
    a, b = data[2 + 2 * i], data[3 + 2 * i]
    score[a] -= 1
    score[b] += 1
judge = -1
for i in range(1, n + 1):
    if score[i] == n - 1:
        judge = i
        break
print(judge)

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int m = (int) in.nval;
        int[] score = new int[n + 1];
        for (int i = 0; i < m; i++) {
            in.nextToken();
            score[(int) in.nval]--;
            in.nextToken();
            score[(int) in.nval]++;
        }
        for (int i = 1; i <= n; i++)
            if (score[i] == n - 1) {
                System.out.println(i);
                return;
            }
        System.out.println(-1);
    }
}

Solve Find the Town Judge online · All practice problems