progress

~/problems / Arrays & hashing / Hash maps and counting

Full path of a folder

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Uber

Folders come as parallel lists: ids[i] (distinct ints), kids[i] (ids directly inside folder i) and names[i]. Folders nobody lists as a child are top-level; there may be several trees, in any order.

Write folder_path(ids, kids, names, target) -> str that returns "/" plus the names from the top-level folder down to target, joined with "/", or "" if target isn't an id.

ids   = [7, 3, 12, 5, 9]
kids  = [[3, 5], [12], [], [], []]
names = ["home", "docs", "taxes", "music", "tmp"]

folder_path(ids, kids, names, 12)   # "/home/docs/taxes"
folder_path(ids, kids, names, 7)    # "/home"
folder_path(ids, kids, names, 9)    # "/tmp"   (another top-level folder)
folder_path(ids, kids, names, 4)    # ""
A folder forest: home (id 7) contains docs (3) and music (5), docs contains taxes (12), and tmp (9) stands alone; the path home, docs, taxes to folder 12 is highlighted

Up to 10**5 folders, possibly one chain that deep (mind Python's recursion limit). ⭐ Bonus: a speed test earns a star if you don't search the lists at each step up.

Show hint

build parent and name dicts in one pass, then walk up from the target and reverse.

Topic: Hash maps and counting. Counter/defaultdict, complement lookups, prefix-sum + hash map.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc