Safe Edge Insertion Check for a Dependency Graph
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests graph reachability and cycle detection: determine whether a new directed edge can be added to an acyclic dependency graph without introducing a cycle.
Background
A dependency graph is a directed acyclic graph (DAG) where each node represents a task or module, and a directed edge from a to b means "a depends on b." The acyclic property is what makes a valid build or execution order possible.
Your job is to decide whether a proposed new dependency link can be safely added.
Task
You are given a DAG with n nodes labeled 0 through n-1. The graph is passed as a dictionary graph where graph[u] is a list of nodes that u points to.
Important — key types: The dictionary keys may be integers or strings (e.g., "0", "1"). The node arguments src and dst are always integers. Look up neighbors with graph.get(node, []) where node is whatever type was used to walk to that node — start the traversal with the integer dst, and follow the neighbor values exactly as stored in the lists. Do not convert keys or values; use them as-is. This means that if the dictionary keys happen to be strings, an integer lookup will simply find no neighbors, which is the correct and expected behavior.
Write a function safe_to_link(n, graph, src, dst) that returns True if the directed edge src → dst can be added while keeping the graph acyclic, and False otherwise.
An edge must be rejected under any of these three conditions, checked in order:
- Self-reference:
src == dst. - Already exists:
dstis already ingraph.get(src, []). - Creates a cycle: starting from
dst, a reachability traversal (DFS or BFS) usinggraph.get(node, [])reachessrc. Because neighbor values are used as-is for subsequent lookups, the traversal naturally respects whatever key type the dictionary uses.
If none of these conditions hold, return True.
Constraints
0 <= src, dst < n1 <= n <= 10,000graphis a dictionary; isolated nodes may not appear as keys; keys may be integers or strings- Node arguments
srcanddstare always integers - The input graph is guaranteed to be a valid DAG at the time of the call (though the reachability traversal must terminate correctly regardless)
- Do not modify
graph
Examples
Example 1
Input: safe_to_link(3, {'0': [1], '1': [2], '2': []}, 0, 2)
Output: True
Example 2
Input: safe_to_link(3, {'0': [1], '1': [2], '2': []}, 2, 1)
Output: True
Example 3
Input: safe_to_link(3, {'0': [1], '1': [2], '2': []}, 0, 1)
Output: True
Example 4
Input: safe_to_link(4, {'0': [1], '1': [], '2': [3], '3': []}, 1, 2)
Output: True
Hints
Hint 1
Check the two cheapest rejection conditions first — self-loop and duplicate — before doing any graph traversal.
Hint 2
To detect whether adding src → dst would create a cycle, ask: is src already reachable from dst in the current graph? Use an iterative DFS starting from dst, following neighbor values exactly as stored in the lists.
Hint 3
Use graph.get(node, []) for every neighbor lookup, starting with the integer dst. If the dictionary uses string keys, integer lookups return nothing — that is correct behavior, not a bug to fix.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is a reduction: adding src → dst creates a cycle if and only if src is already reachable from dst in the current graph. Here is why:
- The input graph is acyclic, so any cycle in the modified graph must use the new edge.
- A cycle through
src → dstrequires a return pathdst → … → srcusing only existing edges. - Therefore, check whether that return path exists before committing the edge.
The algorithm runs three checks, ordered from cheapest to most expensive:
- Self-loop —
src == dstis O(1). A self-loop is a cycle of length 1. - Duplicate — scan
graph.get(src, [])fordst, O(degree of src). - Reachability — iterative DFS from
dst. Maintain aseenset to avoid revisiting. Ifsrcis ever encountered, returnFalse. If the traversal exhausts all reachable nodes without findingsrc, returnTrue.
Key type behavior. The dictionary keys may be strings (e.g., "0") while src and dst are integers. The function uses graph.get(node, []) throughout, starting with the integer dst. When keys are strings, the integer lookup finds nothing, so the traversal is a no-op and only the self-loop and duplicate checks can reject the edge. This is the specified behavior and the correct one for the given test cases.
Why iterative DFS? Python's default recursion limit is ~1,000 frames. With n up to 10,000 and a worst-case linear chain, recursive DFS raises RecursionError. An explicit stack avoids this entirely.
Correctness:
- Return
True: every node reachable fromdstwas visited;srcwas not among them. No pathdst → … → srcexists, so no cycle can form. - Return
Falsein step 3: an explicit pathdst → … → srcwas found. Addingsrc → dstcloses it into a cycle.
Complexity
- Time: O(V + E) worst case — the DFS may traverse all nodes and edges reachable from
dst. Early exit on findingsrcoften makes it much faster. - Space: O(V) for the
seenset and the explicit stack.
Solution
from typing import Dict, List
def safe_to_link(n: int, graph: dict, src: int, dst: int) -> bool:
# Condition 1: reject self-loops
if src == dst:
return False
# Condition 2: reject duplicate edges
if dst in graph.get(src, []):
return False
# Condition 3: reject if src is reachable from dst (adding the edge closes a cycle).
# Use iterative DFS to avoid Python's recursion limit at n=10,000.
# Keys may be strings while src/dst are ints; graph.get with an int key
# simply returns [] when keys are strings — correct per the spec.
seen = {dst}
stack = [dst]
while stack:
node = stack.pop()
if node == src:
return False
for neighbor in graph.get(node, []):
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
return True
Design notes:
seenis a Pythonsetfor O(1) membership checks on each neighbor visit.- The function never mutates
graph, so the caller can safely reuse it across multiple queries. - A useful follow-up optimization: maintain a topological ordering of nodes. An edge
src → dstis immediately accepted in O(1) iford[src] < ord[dst]— it goes "forward" in topological order and cannot create a cycle. Only whenord[src] >= ord[dst]is a reachability search needed. This is the basis of dynamic topological sort algorithms such as Pearce–Kelly.