progress

~/problems / Stateful stores / In-memory file system

Directory tree from paths

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

easy basics ~10 min

Every file-system problem starts by turning a path like "/docs/2024/notes.txt" into a walk through nested dicts: split on "/" and step one dict deeper per name.

Implement FileTree() with:

  • add_file(path, size): store a file of size bytes, creating missing parent directories. An existing file's size is replaced.
  • list_dir(path) -> list[str]: the sorted names of the directory's direct children. "/" is the root.
  • dir_size(path) -> int: the total size of all files anywhere under the directory (0 if empty).
t = FileTree()
t.add_file("/docs/a.txt", 10)
t.add_file("/docs/old/b.txt", 5)
t.add_file("/c.txt", 1)
t.list_dir("/")          # ["c.txt", "docs"]
t.list_dir("/docs")      # ["a.txt", "old"]
t.dir_size("/docs")      # 15
t.dir_size("/")          # 16

Paths are absolute with no trailing slash (except "/"). Queries only name existing directories, and files and directories never collide.

Show hint

a directory is a dict from child name to a dict (subdirectory) or an int (file size); walk it with path.split("/"), skipping empty parts.

Topic: In-memory file system. Path hierarchy as nested dicts; quotas.

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