Amazon interview SDE 2

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2025-02-13Added By Anonymous
Source: Link

Here was the question i got

Question: Design a package installer system that can install a package

along with all its dependencies.


Each package has an "install()" method to install itself.

Implement a solution that, given a package,

installs the given package and its dependencies.


Here is an example of a package structure that we would need to install:

•‘nodejs’ depends on ‘npm’, ‘v8engine’
•‘npm’ depends on ‘nodejs-core’
•‘v8engine’ depends on ‘libuv’
•‘react’ depends on ‘nodejs’, ‘babel’
•‘babel’ depends on ‘core-js’
•‘typescript’ depends on ‘nodejs’

and here's the solution i coded. The solution changed over time, i had to make abunch of assumptions about what the expected input and output should look like


But they had me change my assumptions in the middle of the assesment a few times to make sure i checked for edge cases.

example. I started by saying we're assuming that the input dependency map represents a valid DAG. They said that was fine, but later asked me to assume that it's an arbitrary graph and then handle the case for cycles.

1# runtime O(V + E) 2# space O(E) 3example_dep_map = {'npm' : ['nodejs-core'], 'nodejs' : ['npm', 'v8engine']} 4 5loop_example = {'a': ['b'], 'b': ['a']} 6 7multi_dependents = {'a': ['b', 'c'], 'c' : ['b']} 8 9from something import install, isValidPackage 10 11# visited {'nodejs', 'npm',v8engine , react, babel, typescript } 12# installed {npm, v8engine, nodejs, babel, react, typescript } 13# ordered [nodejs-core, npm, libuv, v8engine, nodejs, corejs, babel, react, typescript ] 14 15def install(dep_map): 16 already_installed = set() 17 visited = set() 18 19 ordered = [] 20 21 def dfs(package_name): 22 if package_name not in dep_map: 23 if not isValidPackage(package_name): 24 throw Exception('undefined package') 25 26 #already_installed.add(package_name) optional 27 ordered.append(package_name) 28 return 29 # 30 31 if package_name in already_installed: 32 return 33 if package_name in visited : 34 throw Exception('error') 35 visited.add(package_name) 36 deps = dep_map[package_name] 37 for d in deps: 38 dfs(d) 39 install(package_name) 40 ordered.append(package_name) 41 already_installed.add(package_name) 42 43 #dfs(package_name) 44 45 for package_name in dep_map.keys(): 46 dfs(package_name) 47 48 return ordered
Comments