KatInterview

Build Installation Order from Package Dependencies

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsgraph-traversaltopological-sortcycle-detection

Last 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)