Validate Adding an Edge to a Directed Acyclic Graph
Hive.AiSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to manipulate graph structures and implement reachability checks, specifically ensuring that adding an edge to a Directed Acyclic Graph (DAG) maintains its acyclic property.
Problem Statement
You are given a Directed Acyclic Graph (DAG) represented by an adjacency list graph, where graph[u] contains a list of all nodes v such that there is a directed edge from u to v.
You are tasked with implementing a function can_add_edge(n, graph, u, v) that determines if a directed edge from node u to node v can be added without violating the DAG property. The graph contains n nodes labeled from 0 to n-1.
Rules for validation:
- No Self-Loops: You cannot add an edge where
u == v. - No Duplicates: You cannot add an edge if the directed edge
(u, v)already exists. - No Cycles: You cannot add the edge
(u, v)if there is already a path fromvtouin the graph.
Function Signature
def can_add_edge(n: int, graph: dict, u: int, v: int) -> bool:
Constraints
0 <= u, v < nncan be up to 10,000.graphis guaranteed to be a valid DAG initially.
Examples
Example 1
- Input:
n = 3,graph = {0: [1], 1: [2], 2: []},u = 0, v = 2 - Output:
True - Explanation: Adding edge 0->2 does not create a cycle. The path 0->1->2 is valid.
Example 2
- Input:
n = 3,graph = {0: [1], 1: [2], 2: [0]},u = 2, v = 1 - Output:
False - Explanation: Adding edge 2->1 would create a cycle because 1 can already reach 2.
Edge Cases
- Disconnected graphs.
- Adding an edge between nodes that have no pre-existing paths.
Hints
Hint 1
Check the trivial conditions (self-loop and duplicate edges) using constant-time lookups before traversing the graph.
Hint 2
To detect if adding (u, v) creates a cycle, you must check if there is an existing path from v to u.
Hint 3
Perform a Breadth-First Search (BFS) or Depth-First Search (DFS) starting from node v to see if you can reach node u.
Follow-up questions
- If we were to actually add the edge, how would you update the graph efficiently?
- What is the time complexity of your solution, and can you optimize it for frequent query operations?
- How would your approach change if the graph were very large and stored on disk, making full traversals expensive?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.