KatInterview

Detect Cycles in a Package Dependency Graph

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphscycle detectiondepth-first search

Last updated

Tests ability to detect cycles in a directed graph using DFS-based cycle detection, modelling package dependencies where a cycle makes installation impossible.

Package Dependency Validator

You are building a package manager. Each package may declare that it must be installed before certain other packages. Given a list of such "must come before" rules, determine whether it is possible to install all packages without contradiction.

A contradiction occurs when the dependency rules form a cycle — for example, package A requires B, B requires C, and C requires A again. In that case, it is impossible to satisfy all requirements.

You are given:

  • n — the total number of packages, identified by integers 0 through n - 1.
  • dependencies — a list of pairs [a, b] meaning package a must be installed before package b.

Return True if the packages can all be installed (no cycle exists), or False if a cycle makes it impossible.

Notes

  • There may be packages with no dependencies at all.
  • There may be duplicate dependency pairs in the input; treat them as a single edge.
  • The graph may be disconnected (some packages are independent of others).
  • Self-loops (a pair [a, a]) count as a cycle.

Constraints

  • 1 <= n <= 2000
  • 0 <= len(dependencies) <= 10000
  • Each pair [a, b] satisfies 0 <= a, b <= n - 1

Examples

Example 1

Input: can_install_all(4, [[0, 1], [1, 2], [2, 3]])

Output: True

Example 2

Input: can_install_all(3, [[0, 1], [1, 2], [2, 0]])

Output: False

Example 3

Input: can_install_all(1, [])

Output: True

Hints

Hint 1

Build a directed adjacency list from the dependency pairs, then think about what it means to traverse it depth-first.

Hint 2

During DFS, maintain two sets: nodes fully processed (done) and nodes on the current recursion stack (in-progress). A back edge — reaching an in-progress node — signals a cycle.

Hint 3

Iterate over every node as a potential DFS start so that disconnected components are all checked.