Folder path from a node id
I was asked this
No reports yet. Sign in to say where you were asked it.
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 folderidList[i]. -
nameList[i]is the display name of folderidList[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 -> parentmap and anid -> namemap 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 returnsNonefor 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
