DAG Graph Leave nodes
Anonymous User
189

This is a practical problem appeared in an interview. It's similar to the tree context as well.
We start with an empty graph and call add_edge(node1, node2) to add edges. There is another method get_leaves(node)
to retrieve the leaves under the node(i.e., start from this node and can reach those leaves).
The question is how we engineer it such that it runs fast: (many = millions of times)

  1. if we call get_leaves(node) many more times than add_edge(node1, node2)
  2. if we call both methods same many times.

I know we could cache some intermediate results to make it fast, but how fast we could get? O(1), O(logn), or O(n).
Binary Index Tree can get O(logn) for updates and queries in arrays context. But this is a graph context, we may have
diamond case (e.g., 1 grand parent to 2 parents then to 1 child).

If we cache relations from node to children and node to parents, we could get O(n). Can we do better than this?

Comments (1)