Flatten a directory listing into paths

Python data engineering interview problem. Difficulty: intermediate. Pattern: Recursion. About 15 minutes. Part of the Pro drill bank.

A directory listing is a nested tree. A backup tool wants a flat list of paths like 'src/app/main.py'.

A file explorer stores a folder tree as nested dictionaries. A folder is a dictionary of names, and a file is shown as None. Turn the tree into a sorted list of full path strings for every file, joining folder names with /. A folder with no files adds no path. An empty tree gives []. Write flatten_dir(tree, prefix=''). {'a': {'b': None, 'c': None}, 'd': None} becomes ['a/b', 'a/c', 'd']. An empty dictionary gives []. The starter file already has the function name and its print lines. Keep them and fill in the body.

Requirements

  • Visit every folder and file.
  • Join names with /.
  • Return only files (leaves), not folders.
  • Return the paths sorted.

Constraints

  • A file is None and a folder is a dictionary.
  • prefix is the path to put in front of everything (empty by default).

Examples

Input: flatten_dir({'a': {'b': None, 'c': None}, 'd': None}) Output: ['a/b', 'a/c', 'd'] This input follows the stated rules and produces this output.

Topics: lakebench, python, recursion.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Flatten a directory listing into paths

Interview-style drill: Given a nested dict representing folders and files, return every full file path.

Flatten a nested directory listing into path strings.