689. All Ancestors

A software company tracks which build jobs must finish before others can start. There are n jobs labelled 0 to n - 1, and each entry [a, b] of edges says that job a must finish directly before job b. The dependencies never form a cycle.

Job x is an ancestor of job y if you can get from x to y by following one or more dependencies. Return a list of n lists, where entry y holds every ancestor of job y in increasing order (an empty list when there are none). Duplicate dependencies may appear, and a job is never its own ancestor. Aim for O(n * (n + m)) time, where m = edges.length.

Example 1

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

Job 0 is reached from 2 and 4 directly, and from 5, 3 and 1 through longer chains, so its ancestors are 1 to 5. Jobs 1 and 5 have no incoming dependencies.

Example 2

Input:
n = 5, edges = [[0,1],[0,2],[1,3],[2,3],[3,4]]
Output:
[[],[0],[0],[0,1,2],[0,1,2,3]]
Explanation:

Job 3 can be reached from 1 and 2 directly and from 0 through either of them, so its ancestors are 0, 1 and 2; job 4 additionally has 3.

Example 3

Input:
n = 3, edges = []
Output:
[[],[],[]]
Explanation:

With no dependencies at all, every job has an empty ancestor list.

Constraints

1 ≤ n ≤ 600

0 ≤ edges.length ≤ 1500

0 ≤ a, b < n and a ≠ b for every edge [a, b]

The graph described by edges contains no directed cycle.

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 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n * (n + m))
Space
O(n^2)

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…