KatInterview

Build a Visual Directory Tree from Nested Dictionary

Trees & GraphsAuto-graded · 14 test cases
MediumAuto-gradedTrees & Graphsrecursiontree-traversalstrings

Last updated

Tests recursion, dictionary traversal, and string formatting to produce an indented tree structure with box-drawing connectors.

You are given a nested dictionary representing a filesystem structure and the name of the root directory. Your task is to generate a visual tree representation returned as a list of strings, where each string is one line of the tree.

Structure

  • Files are represented by keys whose values are None.
  • Directories are represented by keys whose values are dictionaries (possibly empty).
  • Directory names in the output must end with a trailing /.

Formatting Rules

  1. The first line is always the root directory name followed by /.
  2. Each subsequent entry uses tree-drawing characters:
    • ├── when the entry has siblings below it.
    • └── when the entry is the last child in its directory.
  3. Indentation for nested entries uses:
    • │ (vertical bar + three spaces) to continue a line from an ancestor that has remaining siblings.
    • (four spaces) when an ancestor was the last child.
  4. Entries within each directory must be sorted alphabetically (case-sensitive).
  5. Hidden entries (names starting with .) must be excluded from the output entirely.

Constraints

  • 1 ≤ len(root_name) ≤ 100
  • 0 ≤ total number of entries ≤ 1000
  • Entry names contain only alphanumeric characters, underscores, dots, and hyphens.
  • The structure is acyclic (no circular references).
  • Nesting depth will not exceed 50 levels.

Examples

Example 1

Input: build_tree_lines('root', {'config.json': None, 'src': {'index.js': None, 'utils.js': None}, 'README.md': None})

Output: ['root/', '├── README.md', '├── config.json', '└── src/', ' ├── index.js', ' └── utils.js']

Example 2

Input: build_tree_lines('project', {'empty': {}, 'visible.txt': None, '.git': {'config': None}})

Output: ['project/', '├── empty/', '└── visible.txt']

Hints

Hint 1

Think of this as a depth-first traversal where each directory's children are processed in sorted order.

Hint 2

The prefix string accumulates as you recurse deeper: add either a vertical bar with spaces or just spaces depending on whether the parent has more siblings.

Hint 3

Filter out hidden entries before sorting and before determining which child is last.