← Questions

Folder path from a node id

0
UberCoding

A coding interview question asked at Uber. It tests trees, hash map and graph traversal.

A file browser stores its folder hierarchy as three parallel arrays:

  • idList[i] is a unique folder id.
  • children[i] lists the ids of the folders directly inside folder idList[i].
  • nameList[i] is the display name of folder idList[i].

Every folder has at most one parent, so the folders form a forest. A folder that is not inside any other folder is top-level.

Implement folder_path(idList, children, nameList, targetId). It returns the full path of targetId as a string that starts at its top-level folder, with names separated by / and a leading /. Return None (or an empty value in your language) if targetId is not a folder.

Constraints:

  • Up to 10^5 folders; a single chain can be that deep.
  • Names are not unique; ids are.
  • Be ready to answer many queries against the same hierarchy.

Example 1

idList   = [10, 20, 30, 40, 50, 60]
children = [[20, 30], [40], [], [], [60], []]
nameList = ["home", "projects", "music", "compass", "tmp", "cache"]
targetId = 40

Output: "/home/projects/compass". Folder 40 is inside 20, which is inside the top-level folder 10.

Example 2

Same hierarchy, targetId = 60. Output: "/tmp/cache". Folder 50 is a second top-level folder.

Clarifying questions

  • Can the children lists name an id that is not in idList, and what should happen then?
  • Could the data contain a cycle by mistake, and should that be detected?
  • Is the path for a top-level folder just "/name"?
  • How many queries arrive per hierarchy: is pre-processing worth it?

What a strong answer covers

  • Builds a child -> parent map and an id -> name map in one pass, O(n).
  • Answers a query by walking parents up to a top-level folder, collecting names, then reversing: O(depth) per query.
  • For many queries on a deep hierarchy, memoises each folder's path (or stores depth and parent arrays) so repeated walks are not quadratic.
  • Joins names with / once at the end, and returns None for an unknown id.
  • Tests both examples, a deep chain, duplicate names, and an unknown id.

Follow-ups

  • Return the folder id for a given path (the reverse lookup, with duplicate names in mind).
  • Folders can be moved or renamed between queries.
  • Detect and report cycles in malformed input.

Where it's asked

What it tests

trees · hash map · graph traversal

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding