Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Build an NPM Dependency Tree Program

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Build an NPM Dependency Tree Program. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Snyk analyzes NPM dependency graphs to help identify vulnerable transitive packages. Given a root package and its direct dependencies, produce a readable dependency tree using depth-first traversal.

Return a list of output lines. Each dependency must appear beneath its parent with two spaces of indentation per depth level. Preserve the dependency order supplied in the input. A package missing from the dependency map is a leaf package.

If a package appears again while it is already on the current traversal path, append (cycle) to that line and do not traverse its dependencies again. The same package may legitimately appear in multiple separate branches, so only packages on the current path count as cycles.

Formal Specification

Implement build_dependency_tree(root, dependencies), where root is a string and dependencies is a dictionary mapping package names to lists of direct dependency names. Return a list of strings, with the root as the first line. The caller can print the tree with print("\ ".join(result)).

Constraints

  • 1 <= number of reachable package occurrences <= 10^4
  • Package names are non-empty strings
  • Each dependency list preserves the required display order
  • The dependency graph may contain cycles
  • Package names may occur in multiple independent branches

Function Signature

def build_dependency_tree(root, dependencies):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output