683. Fewest Terms

A coding bootcamp offers n modules numbered 1 to n. Each entry [a, b] in relations says module a must be completed in an earlier term than module b. A student may take any number of modules in one term, provided every module they depend on was finished in a previous term.

Return the smallest number of terms needed to finish all modules, or -1 if the relations contradict each other so that some module can never be taken. Relations may repeat, and modules that appear in no relation can be taken in the very first term.

Target O(n + m) time for m relations.

Example 1

Input:
n = 6, relations = [[1,3],[2,3],[3,4],[3,5]]
Output:
3
Explanation:

Modules 1, 2 and 6 have no prerequisites (term 1), module 3 follows (term 2), and modules 4 and 5 finish in term 3.

Example 2

Input:
n = 3, relations = [[1,2],[2,3],[3,1]]
Output:
-1
Explanation:

The three modules wait for each other in a circle, so they can never be completed.

Example 3

Input:
n = 4, relations = []
Output:
1
Explanation:

No relations, so all four modules fit in one term.

Constraints

1 ≤ n ≤ 100000

0 ≤ relations.length ≤ 200000

relations[i] = [a, b] with 1 ≤ a, b ≤ n; pairs may repeat and a may equal b

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n + m)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…