KatInterview

Find All Downstream Dependents in a Dependency Graph

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraph-traversalbfsdirected-graph

Last updated

Tests graph traversal with edge reversal to find all nodes reachable through reversed dependency edges, handling cycles correctly.

You are analyzing a system where components have dependencies on one another. Each dependency is represented as a pair (component_x, component_y), meaning that component_x relies on component_y.

When component_y is modified, every component that relies on it—either directly or through a chain of dependencies—may need attention.

Write a function that accepts a list of dependency pairs and a specific component that has been changed, then returns all components that depend on the changed component, directly or indirectly.

Important: Do not include the changed component itself in the output, even if circular dependencies exist.

Input

  • dependencies: A list of pairs [component_x, component_y] where component_x depends on component_y
  • changed_component: The component that was modified (a string)

Output

Return a list of component names (strings) representing all components that depend on changed_component. The order of components in the output does not matter.

Constraints

  • The dependency graph may contain cycles (circular dependencies between components)
  • The total number of components and dependency relationships will not exceed 10,000
  • Component names are non-empty strings
  • The changed_component may or may not appear in the dependency list
  • Self-dependencies (a component depending on itself) are possible

Examples

Example 1

Input: find_dependent_components([['A', 'B'], ['B', 'C']], 'C')

Output: ['B', 'A']

Example 2

Input: find_dependent_components([['A', 'B'], ['B', 'A'], ['C', 'B']], 'A')

Output: ['B', 'C']

Hints

Hint 1

The direction of edges in the input is opposite to the direction impact flows. If A depends on B, then changes to B impact A.

Hint 2

Build a reverse graph where each component points to all components that depend on it, then traverse from the changed component.

Hint 3

Use BFS or DFS with a visited set to handle cycles. Mark the starting component as visited immediately to exclude it from results.