All Ancestors of a Node in a Directed Acyclic Graph

For every node of a graph whose one-way links never form a circle, list all the nodes that can reach it.

A graph has n nodes, numbered 0 to n - 1, and a list edges. Each pair [a, b] in edges is a one-way link from node a to node b, and following the links never brings you back to a node you already passed. For every node, return its ancestors in ascending order. A node is an ancestor of another node when following links leads from the ancestor down to that node.

Example 1
Input: n = 8, edges = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
Explanation: 6 can be reached from 3 and 4, and through them from 0, 1 and 2.
Example 2
Input: n = 5, edges = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]]
Explanation: every node has a link to every bigger node, so each node's ancestors are all the smaller nodes.
Solution

The Idea

Picture streams running downhill. Water flows from one point to the next, never back up, so it can never go round in a circle. The ancestors of a point are all the points upstream of it: the places whose water passes through it sooner or later.

The problem uses the usual words for this. The points are nodes and the one-way links are edges. A graph whose edges go one way only is called directed, and one where you can never return to a node you passed is called acyclic, meaning without cycles. Together that is a directed acyclic graph, or DAG for short.

Take node 6 in Example 1. Two edges lead into it, from 3 and from 4. Edges lead into 3 from 0 and 1, and into 4 from 0 and 2. So the nodes upstream of 6 are 0, 1, 2, 3 and 4, which is the list [0,1,2,3,4] in the output.

That walk went backwards, against the edges, and it met the ancestors in the order 3, 4, 0, 1, 0, 2. Node 0 showed up twice, and the list still had to be sorted. Is there a way to collect the ancestors that avoids both?

Turn the question around. Instead of asking which nodes are upstream of 6, ask where the water from node 0 goes. Look at the picture below.

The graph of Example 1. A search starts at node 0 and follows the edges forwards to 3 and 4, then on to 5, 6 and 7. Each of them gets 0 in its ancestor list. Node 6 is reached twice, through 3 and through 4.

Starting at 0, the orange edges lead to 3 and 4, and from there to 5, 6 and 7. Every node coloured orange can be reached from 0, so each of them gets 0 in its ancestor list. Node 6 is reached twice, once through 3 and once through 4, so the search has to remember the nodes it has already seen.

Now do the same from node 1, then from node 2, and so on up to the last node. Each start node is added to the lists of the nodes it reaches, and the start nodes come in increasing order. So every list fills up in increasing order too, and no sort is needed at the end.

Solution Approach

Turning that idea into code means settling four things: how to store the edges, how to walk from one start node, how to avoid adding an ancestor twice, and why the lists need no sort.

Storing the edges

Where does a search look up the nodes an edge leads to? The input is just a list of pairs, so first it is turned into one list per node, holding the nodes that node's edges point to. These are the node's children. For Example 1 the lists are:

  • 0: [3, 4], 1: [3], 2: [4, 7]
  • 3: [5, 6, 7], 4: [6]
  • 5, 6 and 7: empty

Keeping one list of neighbours per node like this is called an adjacency list. Each pair goes into the list of its first node only, because the search only walks edges forwards.

Walking from one start node

How does a search from 0 reach everything downstream? It follows one path as deep as it goes, then backs up to the last node that still has an unexplored child. In the picture, a search could go 0, 3, 5, back up to 3 for 6 and 7, then over to 4. Searching in this way is called depth-first search, or DFS. Which child is tried first does not change which nodes get reached.

The nodes still waiting to be explored go on a stack, a pile where the node put on last is taken off first. Java's ArrayDeque works as one with push and pop. A method that calls itself for each child would do the same job, but on a long chain it nests one call inside another for every node. The ArrayDeque keeps that depth in an ordinary object instead.

Not adding an ancestor twice

What stops node 6 from getting 0 twice? Each search keeps a boolean array, named visited, with one entry per node. A node is marked when the search first reaches it, and a marked node is skipped. The array starts fresh for every start node, because 6 being reached from 0 says nothing about whether 1 reaches it.

Why the lists come out sorted

The searches run from start node 0, then 1, then 2, and each adds only its own start node to the lists. So a list receives 0 before 1, 1 before 2, and so on. This does not depend on which way the edges point, only on the order of the start nodes. The backward walk from the Idea finds the same ancestors, but would need a sort for every list.

Java Solution

The method getAncestors works in these steps:

  1. First, create two lists of lists, children and ancestors, with one empty list per node. ancestors becomes the answer. Then, for every edge e, add e[1] to the children of e[0].
  2. Run one search per start node with a loop, moving src from 0 up to n - 1. For each src, create a fresh visited array and a stack holding only src, and mark src as visited.
  3. While the stack is not empty, pop a node u and look at each of its children v. If v is not visited yet, mark it, add src to the ancestors of v, and push v so its own children get explored.
  4. When the last search is done, return ancestors.

The main method runs both examples and a diamond where 0 reaches 3 through both 1 and 2. Then it tries three nodes with no edges, and a chain whose edges point downwards, from 3 to 2 to 1 to 0.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class AllAncestorsOfNodeInDAG {

    public static List<List<Integer>> getAncestors(int n, int[][] edges) {
        List<List<Integer>> children = new ArrayList<>();
        List<List<Integer>> ancestors = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            children.add(new ArrayList<>());
            ancestors.add(new ArrayList<>());
        }
        for (int[] e : edges) {
            children.get(e[0]).add(e[1]);           // edge from e[0] to e[1]
        }
        for (int src = 0; src < n; src++) {         // start nodes in increasing order
            boolean[] visited = new boolean[n];     // fresh for every search
            Deque<Integer> stack = new ArrayDeque<>();
            stack.push(src);
            visited[src] = true;
            while (!stack.isEmpty()) {
                int u = stack.pop();
                for (int v : children.get(u)) {
                    if (!visited[v]) {
                        visited[v] = true;
                        ancestors.get(v).add(src);  // src can reach v
                        stack.push(v);
                    }
                }
            }
        }
        return ancestors;
    }

    public static void main(String[] args) {
        System.out.println(getAncestors(8, new int[][] {{0, 3}, {0, 4}, {1, 3}, {2, 4}, {2, 7},
                {3, 5}, {3, 6}, {3, 7}, {4, 6}}));
        System.out.println(getAncestors(5, new int[][] {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {1, 2},
                {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}));
        System.out.println(getAncestors(4, new int[][] {{0, 1}, {0, 2}, {1, 3}, {2, 3}}));
        System.out.println(getAncestors(3, new int[][] {}));
        System.out.println(getAncestors(4, new int[][] {{3, 2}, {2, 1}, {1, 0}}));
    }
}

Running it prints:

Output
[[], [], [], [0, 1], [0, 2], [0, 1, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3]]
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
[[], [0], [0], [0, 1, 2]]
[[], [], []]
[[1, 2, 3], [2, 3], [3], []]

The first line is Example 1, with [0, 1, 2, 3, 4] for node 6 and the start nodes in increasing order in every list. The third line is the diamond: node 3 gets [0, 1, 2], with 0 listed once although the search from 0 reaches 3 through both 1 and 2. The fourth line shows three empty lists, since without edges no node can reach another.

Look at the last line, [[1, 2, 3], [2, 3], [3], []]. Every edge points down, yet node 0's list is still in ascending order. The search from 1 added 1, the one from 2 added 2, and the one from 3 added 3, in that order.

Does the visited check matter when the graph has no cycles? Without it, every search still ends, but a node reached by two routes gets the start node twice. A run of Example 1 with the check removed gives [0, 0, 1, 2, 3, 4] for node 6.

Complexity

The work is n searches, and each one walks only the part of the graph that its start node can reach.

  • Time: O(n × (n + m)), with m the number of edges, because each of the n searches sets up a visited array of n entries and follows each edge at most once.
  • Space: O(n2), because when every node reaches every bigger node, as in Example 2, the output holds n(n - 1)/2 ancestors, and the other structures add only O(n + m).

The search used here is explained on its own in Depth First Search.