Build Installation Order from Package Dependencies
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests graph traversal with cycle detection to compute a valid installation sequence for packages with dependencies.
Problem Statement
You are building a package manager that needs to determine the correct installation order for software packages. Given a target package and a mapping of package dependencies, compute the sequence in which packages must be installed so that each package is installed only after all its dependencies are already in place.
You are given a dictionary dependencies where each key is a package name (string) and the corresponding value is a list of package names (strings) that must be installed before it. A package that does not appear as a key in the dictionary is assumed to have no dependencies.
Write a function installation_order(target, dependencies) that returns a list of package names representing a valid installation sequence for the target package. Every dependency must appear in the list before any package that requires it. If a circular dependency is detected (package A depends on B, which depends on A, directly or indirectly), return an empty list to indicate the impossibility of a valid installation order.
Constraints
- The dependencies dictionary may contain up to 10,000 packages
- Package names are non-empty strings
- Circular dependencies must be detected and handled correctly
- A package not present in the dictionary keys is treated as having zero dependencies (a leaf node)
- The same dependency may appear multiple times in a package's dependency list
- Dependency chains may be arbitrarily deep
Notes
- Only packages reachable from the target (the target itself and its transitive dependencies) should appear in the output
- Each package should appear exactly once in the output list
- If multiple valid orderings exist, any one of them is acceptable
Examples
Example 1
Input: installation_order('A', {'A': ['B', 'C'], 'B': ['C'], 'C': []})
Output: ['C', 'B', 'A']
Example 2
Input: installation_order('A', {'A': ['B'], 'B': ['A']})
Output: []
Example 3
Input: installation_order('A', {'A': ['B', 'C'], 'B': []})
Output: ['B', 'C', 'A']
Example 4
Input: installation_order('A', {'A': []})
Output: ['A']
Hints
Hint 1
Model the packages and dependencies as a directed graph where an edge from A to B means A requires B to be installed first
Hint 2
Use depth-first search with a state-tracking mechanism to detect when you revisit a node that is still being processed (a back edge indicates a cycle)
Hint 3
Append each package to the result only after all of its dependencies have been fully processed (post-order traversal)
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires computing a topological ordering of a directed graph while detecting cycles. We model packages as nodes and dependencies as directed edges: if package A depends on package B, we draw an edge from A to B, meaning B must be installed before A.
The solution uses depth-first search with three-state tracking:
- Unvisited (0): The package has not been explored yet
- Processing (1): We are currently exploring this package and its dependencies
- Completed (2): All dependencies have been processed and the package has been added to the result
When we encounter a package in the "processing" state during traversal, we've found a back edge, indicating a cycle. If we reach a "completed" package, we skip it since it's already in the result.
The key insight is to use post-order traversal: we add a package to the result only after recursively processing all its dependencies. This guarantees that every dependency appears before the packages that need it.
Why It Works
- Correctness of ordering: A package is added to the result only after all its dependencies return successfully, ensuring dependencies precede their dependents
- Cycle detection: The three states distinguish between "not yet visited," "currently on the recursion path," and "fully processed." Reaching a package that's currently on the path proves a cycle exists
- Completeness: DFS explores every package reachable from the target, ensuring all transitive dependencies are included
- No duplicates: Each package transitions from unvisited → processing → completed exactly once, so it appears in the result exactly once
Complexity
Time: O(V + E) where V is the number of reachable packages and E is the number of dependency edges among them. Each package is visited once, and each edge is examined once.
Space: O(V) for the status dictionary and result list, plus O(D) recursion stack depth where D is the longest dependency chain.
Solution Code
from typing import Dict, List
def installation_order(target: str, dependencies: Dict[str, List[str]]) -> List[str]:
result = []
status = {} # 0=unvisited, 1=currently processing, 2=completed
def dfs(pkg):
current_status = status.get(pkg, 0)
if current_status == 1:
return False # cycle detected
if current_status == 2:
return True # already processed
status[pkg] = 1
for dep in dependencies.get(pkg, []):
if not dfs(dep):
return False
status[pkg] = 2
result.append(pkg)
return True
if not dfs(target):
return []
return result