Paper Leak Simulator: Find the Mastermind

The National Examination Authority (NEA) is investigating a suspected leak of the question paper.

There are n students labeled from 0 to n - 1.

You are given a list of directed edges leaks, where leaks[i] = [u, v] indicates that student u shared the leaked paper with student v.

The investigation team defines a student as the Mastermind if:

  1. They received the paper from no one.
  2. Every other student received the paper directly or indirectly because of them.

Your task is to identify the Mastermind behind the leak.

Return the index of the Mastermind if exactly one such student exists. Otherwise, return -1.


Example 1

Input

n = 4
leaks = [[0,1],[1,2],[2,3]]

Output

0

Explanation

Student 0 started the leak.

The paper was forwarded as:

0 → 1 → 2 → 3

Every student eventually received the paper because of student 0.


Example 2

Input

n = 4
leaks = [[0,1],[2,1],[1,3]]

Output

-1

Explanation

Both students 0 and 2 have not received the paper from anyone.

Since there is no unique source of the leak, no Mastermind can be identified.


Example 3

Input

n = 5
leaks = [[2,0],[2,1],[2,3],[3,4]]

Output

2

Explanation

      2
   /  |  \
  0   1   3
           \
            4

Student 2 is the only student with no incoming leaks and every other student can be reached from them.

Therefore, the Mastermind is 2

Constraints

1 <= n <= 10^5
0 <= leaks.length <= 10^5
leaks[i].length == 2
0 <= u, v < n
u != v

If you solve it or have suggestions for improvement, let me know in the comments.
If you enjoyed the problem, an upvote would be appreciated.

Comments (7)