KatInterview

Collect Every File Path from a Nested Directory Tree

Trees & GraphsAuto-graded · 17 test cases
EasyAuto-gradedTrees & Graphsdfstree-traversalrecursion

Last updated

Traverse a nested directory dictionary depth-first and build the full slash-joined path for each file, following precise joining and ordering rules.

Collect Every File Path from a Nested Directory Tree

A file system is described as a nested dictionary. Each node has these keys:

  • name: a string, the name of this file or directory.
  • isFile: a boolean, true for a file and false for a directory.
  • children: a list of child nodes. It is empty for files, and it may be missing entirely, in which case treat it as empty.

The top-level dictionary is the root directory.

Write a function that returns the full path of every file in the tree, as a list of strings.

Path rules

  • The path of the root is just its name.
  • The path of any other node is parent_path + "/" + name.
  • Exception: if parent_path is the empty string, the node's path is just its name, with no leading /.
  • Names are used exactly as given. Do not trim, normalize, or collapse slashes. For example, a root named "/" with a file file.txt gives "//file.txt".

Output rules

  • Include only files. Directories never appear in the output, and empty directories contribute nothing.
  • Visit nodes depth-first in pre-order, handling each node's children in the order they are listed. Return the paths in the order the files are encountered.
  • If the root itself is a file, return a list containing only its name.

Constraints

  • The tree has at least one node (the root).
  • Every node has a string name and a boolean isFile.
  • Files have no children.
  • Names are arbitrary strings, possibly containing /, and are used verbatim.
  • Recursion depth is modest, so a recursive DFS is acceptable.

Examples

Example 1

Input: collect_file_paths({'name': 'root', 'isFile': False, 'children': [{'name': 'a', 'isFile': False, 'children': [{'name': 'b.txt', 'isFile': True, 'children': []}, {'name': 'c', 'isFile': False, 'children': [{'name': 'd.md', 'isFile': True, 'children': []}]}]}, {'name': 'e.log', 'isFile': True, 'children': []}]})

Output: ['root/a/b.txt', 'root/a/c/d.md', 'root/e.log']

Example 2

Input: collect_file_paths({'name': '/', 'isFile': False, 'children': [{'name': 'file.txt', 'isFile': True, 'children': []}]})

Output: ['//file.txt']

Hints

Hint 1

Think of the path as something you carry down as you move from a node to its children, rather than something you rebuild from scratch.

Hint 2

At each node, compute its own path from the parent's path. If the node is a file, record the path and stop. Otherwise recurse into each child in order.

Hint 3

Watch the joining rule: when the parent path is empty, use the name alone. Do not strip or clean the root name, because a root of "/" must produce "//file.txt".