![]() |
VOOZH | about |
Given a directed acyclic graph (DAG) represented as an adjacency list adj[][], where adj[u] contains all nodes v such that there is a directed edge from u to v, find the maximum number of additional edges that can be added without creating any cycles.
Note: The resulting graph should remain a DAG, meaning that adding any further edge would introduce a cycle.
Examples:
Input: adj[][] = [[1], [2], []]
Output: 1
Explanation: The given DAG allows one more edge, 0 -> 2, which keeps the structure acyclic. Adding anything else would create a cycle.Input: adj[][] = [[1, 2], [2], [3], []]
Output: 2
Explanation: Two additional edges (0 -> 3, 1 -> 3) can be added without forming cycles.
Table of Content
The idea is to first find a topological order of the graph because this order tells us which nodes must come before others. In a DAG, a node can only have outgoing edges to nodes that appear later in the topological order.
Once we have the topological order, we can safely add an edge from a node u to a node v if v comes after u in the order and there is no existing edge between them. This ensures that no cycles are introduced, because edges are always going “forward” in the topological order.
By checking all such forward pairs (u, v) and counting the ones not already connected, we can determine the maximum number of edges that can be added without creating cycles.
2
Time Complexity: O(V2), where V is number of Vertices
Auxiliary Space: O(V2)
In a DAG with V nodes, the maximum number of edges is V * (V - 1) / 2, representing all possible forward edges in a topological order. To find the maximum number of additional edges, simply subtract the current number of edges in the graph from maximum no of edges possible.
2