Render Indented Directory Tree From Paths

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a collection of absolute path strings describing folders and files under an implicit root "/", implement print_file_system_state(paths: List[str]) -> str to render the entire hierarchy as an indented text outline.

Apply these formatting and classification rules:

  • Folder vs. file classification: A path with a trailing slash "/" (such as "/etc/nginx/certs/") explicitly designates its final segment as a folder, even when empty. Any segment that has child entries beneath it is likewise a folder (even if another input string listed that same prefix without a trailing slash). All remaining leaf segments without a trailing slash are files.
  • Deduplication: Repeated paths or shared ancestor prefixes collapse into the same node in the hierarchy and appear only once.
  • Sibling ordering: Within every parent folder (including the top level directly beneath "/"), list all folders ahead of all files. Sort folders in standard ASCII lexicographical order among themselves, and sort files in standard ASCII lexicographical order among themselves.
  • Indentation and line breaks: Emit one segment name per line (omitting "/" separators), indented by two spaces (" ") multiplied by its 0-based depth (0 spaces for top-level entries). Join lines with "\n" and do not append a trailing newline.

Examples

Example 1

Input:
  paths = [
      "/etc/nginx/sites/default.conf",
      "/etc/nginx/certs/",
      "/etc/hosts",
      "/opt/bin/run.sh"
  ]

Output:
etc
  nginx
    certs
    sites
      default.conf
  hosts
opt
  bin
    run.sh

Explanation: At depth 0, top-level folders etc and opt sort alphabetically. Inside etc, folder nginx precedes file hosts even though 'h' comes before 'n'. Inside nginx, empty folder certs (marked by its trailing "/") sorts ahead of folder sites.

Example 2

Input:
  paths = [
      "/srv/zebra/",
      "/srv/alpha.log",
      "/srv/beta.log",
      "/backup/",
      "/license.txt"
  ]

Output:
backup
srv
  zebra
  alpha.log
  beta.log
license.txt

Explanation: At the root level, folders backup and srv appear before top-level file license.txt. Inside srv, subfolder zebra is listed ahead of both .log files despite starting with 'z'.

Example 3

Input:
  paths = ["/Makefile"]

Output:
Makefile

Explanation: A single top-level file sits at depth 0 with zero leading spaces and no trailing newline.

Example 4

Input:
  paths = [
      "/pkg/core/init.py",
      "/pkg/cli.py",
      "/pkg/plugins/",
      "/tests/init.py"
  ]

Output:
pkg
  core
    init.py
  plugins
  cli.py
tests
  init.py

Explanation: Identical filenames (init.py) under distinct folders (core and tests) remain separate entries, and inside pkg both subfolders (core, plugins) precede cli.py.

Constraints

  • 1 <= len(paths) <= 1000
  • Every element of paths is a valid "/"-delimited path starting from "/" with at least one non-empty component.
  • Path depth can exceed 1000 nested levels.

Step-by-step walkthrough

  1. Understand the goal and formatting rules

    We receive a list of "/"-separated path strings such as "/etc/nginx/sites/default.conf" and must return one multi-line string visualizing the nested hierarchy:

    • One segment per line: Emit only the segment name on each line (without "/" characters), joined by "\n" with no trailing newline.
    • Two-space indentation: Prefix each line with " " * depth, where entries directly below the implied root "/" sit at depth 0 (zero leading spaces).
    • Folders ahead of files: Inside every parent directory, place all subdirectories first and all files second. Within each group, sort names in standard ASCII alphabetical order ("certs" before "sites").
    • Folder vs. file detection: A trailing "/" (like "/etc/nginx/certs/") explicitly marks certs as a directory even when empty. Any segment that has child entries beneath it (such as etc, nginx, sites, or "b" when both "/a/b" and "/a/b/c" appear) is also a directory.
  2. Why sorting raw path strings fails

    Sorting the raw paths list alphabetically and printing components on the fly breaks down for two reasons:

    1. Plain string order interleaves files and folders: Alphabetical comparison places "/etc/hosts" (a file) ahead of "/etc/nginx/certs/" (a folder) simply because 'h' precedes 'n'.
    2. A single path lacks global context: Reading "/a/b" in isolation makes b look like a file; you only learn b is a directory when "/a/b/c" or "/a/b/" shows up later in paths.
    Seen first:  "/a/b"      -> appears to be a leaf file named b
    Seen later:  "/a/b/c"    -> places child c inside b, upgrading b to a directory!
    

    Consequently, we must ingest every path first to build the complete hierarchy in memory, and sort and format second once every node's final directory status is known.

  3. Represent the hierarchy as a prefix tree

    A directory tree starting from "/" where shared path prefixes (such as "/etc/nginx") map to shared ancestor nodes is a trie (or prefix tree). Re-inserting an identical path simply walks existing nodes without duplicating anything.

    Each TreeNode tracks two fields: - children: a dictionary mapping immediate child names to their TreeNode instances. - marked_dir: a boolean flag set to True whenever at least one input path ended with "/" at this node.

    Splitting "/etc/certs/" on "/" produces ["", "etc", "certs", ""]. Dropping empty strings yields ["etc", "certs"], avoiding bogus "" child nodes while path.endswith("/") records the trailing slash. Notice we only ever set marked_dir = True (never reset it to False), ensuring an earlier "/a/z/" stays a folder even if "/a/z" appears afterward.

    class TreeNode:
        def __init__(self) -> None:
            # children: maps immediate child name -> TreeNode, e.g. {"nginx": TreeNode(), "hosts": TreeNode()}
            self.children: Dict[str, "TreeNode"] = {}
            # marked_dir: True if at least one input path ended with "/" at this node
            self.marked_dir: bool = False
    
        def is_dir(self) -> bool:
            # A node is a directory if a path explicitly ended with "/" there,
            # OR if another path placed children underneath it.
            return self.marked_dir or len(self.children) > 0
    
    
    def insert_path(root: TreeNode, path: str) -> None:
        """Insert all path components of `path` into the file-system tree."""
        # Split on "/" and drop empty strings caused by leading or trailing slashes,
        # e.g. "/etc/certs/" -> ["etc", "certs"].
        parts: List[str] = []
        for part in path.split("/"):
            if part:
                parts.append(part)
    
        # Walk down from the virtual root, creating any missing nodes along the path.
        current = root
        for part in parts:
            if part not in current.children:
                current.children[part] = TreeNode()
            current = current.children[part]
    
        # Only set marked_dir to True (never reset to False), so an earlier "/a/z/"
        # stays a directory even if "/a/z" appears later without a trailing slash.
        if path.endswith("/"):
            current.marked_dir = True
    
  4. Order siblings inside a single directory

    Once all paths are inserted, child.is_dir() accurately classifies every node. To order the immediate children of node, partition their names into dir_names and file_names, sort each list independently, and concatenate dir_names + file_names so folders always come ahead of files at that depth.

    def get_ordered_children(node: TreeNode) -> List[Tuple[str, TreeNode]]:
        """Return (name, child_node) pairs: directories first, then files, each sorted alphabetically."""
        dir_names: List[str] = []
        file_names: List[str] = []
    
        for name, child in node.children.items():
            if child.is_dir():
                dir_names.append(name)
            else:
                file_names.append(name)
    
        dir_names.sort()
        file_names.sort()
    
        ordered: List[Tuple[str, TreeNode]] = []
        for name in dir_names + file_names:
            ordered.append((name, node.children[name]))
        return ordered
    
  5. Render the tree depth-first with an explicit stack

    Emitting a folder's line and immediately visiting its entire subtree before moving to its next sibling is a pre-order depth-first traversal. While recursion is tempting, Python caps call-stack depth around 1,000 frames by default (sys.getrecursionlimit()), whereas valid inputs can exceed 1,000 nested folders.

    Driving the walk with an explicit stack of (name, node, depth) tuples removes any recursion limit. Because a Python list stack pops from the end (last-in, first-out), we push each node's ordered children in reverse order so the first sorted child sits at the top of the stack and prints next:

    Ordered children of etc:  [("nginx", ...), ("hosts", ...)]
    Push reversed onto stack:
      bottom -> ("hosts", hosts_node, 1)
      top    -> ("nginx", nginx_node, 1)   <-- popped first, along with its entire subtree!
    
    def print_file_system_state(paths: List[str]) -> str:
        root = TreeNode()
        for path in paths:
            insert_path(root, path)
    
        lines: List[str] = []
        stack: List[Tuple[str, TreeNode, int]] = []
    
        for name, child in reversed(get_ordered_children(root)):
            stack.append((name, child, 0))
    
        while stack:
            name, node, depth = stack.pop()
            indent = "  " * depth
            lines.append(indent + name)
    
            for child_name, child_node in reversed(get_ordered_children(node)):
                stack.append((child_name, child_node, depth + 1))
    
        return "\n".join(lines)
    
  6. Trace Example 1 step by step

    Walk through Example 1: paths = ["/etc/nginx/sites/default.conf", "/etc/nginx/certs/", "/etc/hosts", "/opt/bin/run.sh"]

    After Phase 1 inserts all four strings, the prefix tree has this structure:

    (root)
    ├── etc                  [dir: has children "nginx", "hosts"]
    │   ├── nginx            [dir: has children "certs", "sites"]
    │   │   ├── certs        [dir: marked_dir = True from trailing "/"]
    │   │   └── sites        [dir: has child "default.conf"]
    │   │       └── default.conf  [file]
    │   └── hosts            [file]
    └── opt                  [dir: has child "bin"]
        └── bin              [dir: has child "run.sh"]
            └── run.sh       [file]
    

    Now trace Phase 2 (stack shown from bottom to top):

    Step                           Stack (bottom -> top)                     Appended line
    -----------------------------  ----------------------------------------  -------------------
    Init root children reversed    [(opt,0), (etc,0)]                        -
    Pop (etc, 0): nginx < hosts    [(opt,0), (hosts,1), (nginx,1)]           "etc"
    Pop (nginx, 1): certs < sites  [(opt,0), (hosts,1), (sites,2),           "  nginx"
                                             (certs,2)]
    Pop (certs, 2)                 [(opt,0), (hosts,1), (sites,2)]           "    certs"
    Pop (sites, 2)                 [(opt,0), (hosts,1), (default.conf,3)]    "    sites"
    Pop (default.conf, 3)          [(opt,0), (hosts,1)]                      "      default.conf"
    Pop (hosts, 1)                 [(opt,0)]                                 "  hosts"
    Pop (opt, 0)                   [(bin,1)]                                 "opt"
    Pop (bin, 1)                   [(run.sh,2)]                              "  bin"
    Pop (run.sh, 2)                []                                        "    run.sh"
    

    Joining lines with "\n" returns 'etc\n nginx\n certs\n sites\n default.conf\n hosts\nopt\n bin\n run.sh', matching Example 1.

  7. Complete solution

    Combine the node definition, path ingestion, sibling ordering, and iterative pre-order walk:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TreeNode:
        def __init__(self) -> None:
            # children: maps immediate child name -> TreeNode, e.g. {"nginx": TreeNode(), "hosts": TreeNode()}
            self.children: Dict[str, "TreeNode"] = {}
            # marked_dir: True if at least one input path ended with "/" at this node
            self.marked_dir: bool = False
    
        def is_dir(self) -> bool:
            # A node is a directory if a path explicitly ended with "/" there,
            # OR if another path placed children underneath it.
            return self.marked_dir or len(self.children) > 0
    
    
    def insert_path(root: TreeNode, path: str) -> None:
        """Insert all path components of `path` into the file-system tree."""
        # Split on "/" and drop empty strings caused by leading or trailing slashes,
        # e.g. "/etc/certs/" -> ["etc", "certs"].
        parts: List[str] = []
        for part in path.split("/"):
            if part:
                parts.append(part)
    
        # Walk down from the virtual root, creating any missing nodes along the path.
        current = root
        for part in parts:
            if part not in current.children:
                current.children[part] = TreeNode()
            current = current.children[part]
    
        # Only set marked_dir to True (never reset to False), so an earlier "/a/z/"
        # stays a directory even if "/a/z" appears later without a trailing slash.
        if path.endswith("/"):
            current.marked_dir = True
    
    
    def get_ordered_children(node: TreeNode) -> List[Tuple[str, TreeNode]]:
        """Return (name, child_node) pairs: directories first, then files, each sorted alphabetically."""
        dir_names: List[str] = []
        file_names: List[str] = []
    
        for name, child in node.children.items():
            if child.is_dir():
                dir_names.append(name)
            else:
                file_names.append(name)
    
        dir_names.sort()
        file_names.sort()
    
        ordered: List[Tuple[str, TreeNode]] = []
        for name in dir_names + file_names:
            ordered.append((name, node.children[name]))
        return ordered
    
    
    def print_file_system_state(paths: List[str]) -> str:
        # Phase 1: Build the complete tree before sorting so every node knows all its children.
        root = TreeNode()
        for path in paths:
            insert_path(root, path)
    
        # Phase 2: Depth-first traversal using an explicit stack so deeply nested paths
        # (> 1000 levels) cannot hit Python's recursion limit.
        # stack: list of (name, node, depth) tuples, e.g. [("opt", opt_node, 0), ("etc", etc_node, 0)]
        lines: List[str] = []
        stack: List[Tuple[str, TreeNode, int]] = []
    
        # Push children in reverse order because stack.pop() removes from the end (LIFO),
        # ensuring the first sorted child is popped and printed first.
        for name, child in reversed(get_ordered_children(root)):
            stack.append((name, child, 0))
    
        while stack:
            name, node, depth = stack.pop()
            indent = "  " * depth
            lines.append(indent + name)
    
            for child_name, child_node in reversed(get_ordered_children(node)):
                stack.append((child_name, child_node, depth + 1))
    
        # Phase 3: Join all formatted lines with newlines (no trailing newline).
        return "\n".join(lines)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture sorting a stack of loose shipping labels into nested drawer dividers before printing a cabinet directory. First, you file every path into its nested folder hierarchy; second, you open drawers top-down, always listing sub-drawers ahead of individual files inside the same drawer. Merging shared starting segments such as "/etc/nginx" into shared ancestor nodes forms a trie (or prefix tree: a tree structure where stepping down one edge appends one path segment to the prefix).

Why does sorting the raw path strings fall short? Plain string comparison mixes files with folders — for instance, "/etc/hosts" sorts ahead of "/etc/nginx/certs/" even though nginx is a directory and must come before sibling files. Worse still, inspecting "/a/b" in isolation cannot tell you whether b is a file or a folder, because a subsequent entry like "/a/b/c" may place a child under b. Assembling the full tree before sorting resolves both issues cleanly.

Let's trace a compact three-path example: ["/srv/zebra/", "/srv/beta.log", "/srv/alpha.log"]: 1. Inserting all three paths creates one top-level folder srv (a directory because it has children) containing zebra (marked as a directory by its trailing "/"), beta.log (file), and alpha.log (file). 2. Ordering srv's immediate children places sorted folders (["zebra"]) ahead of sorted files (["alpha.log", "beta.log"]), yielding ["zebra", "alpha.log", "beta.log"]. 3. A pre-order traversal (a tree walk that visits each parent node right before visiting its children) emits srv at depth 0, followed by zebra, alpha.log, and beta.log at depth 1.

Complexity

Let L be the sum of character lengths across all strings in paths, N be the number of unique nodes in the constructed prefix tree (N <= L), and P be the character length of the formatted output string.

  • Time: O(L + N log N + P) (counting each segment-name comparison as one operation, or O(L log N + P) in character comparisons). Splitting strings and inserting segments into hash dictionaries touches each of the L input characters a constant number of times. Each node sorts only its immediate children, and since child counts across the whole tree sum to N, all sorting work totals at most O(N log N) comparisons. Assembling indented lines and joining them costs O(P) time; P is tracked explicitly because a single chain of k one-letter folders (L = 2k) emits 0 + 2 + 4 + ... + 2(k - 1) spaces, where P grows quadratically in k.
  • Space: O(L + P). Tree nodes and stored segment names take O(L) memory, the explicit traversal stack holds at most N tuples simultaneously, and the output string occupies O(P) memory.

Edge cases

  • Single root-level file (["/Makefile"], Example 3): Returns "Makefile" with zero indentation and no newline character.
  • Empty folder denoted by trailing slash ("/etc/nginx/certs/", Example 1): Filtering empty strings ignores the trailing "" segment while marked_dir = True preserves directory status with zero children.
  • Segment appearing both as leaf and as folder (["/a/b", "/a/b/c"] or ["/a/z/", "/a/z"]): Having children or marked_dir = True keeps the node classified as a single directory.
  • Repeated paths (["/a/b.txt", "/a/b.txt", "/a/"]): Duplicate insertions reuse existing dictionary keys so every node renders once.
  • Identical names in separate folders (init.py in Example 4): Each parent maintains its own children dictionary, preventing collisions across directories.
  • Deep hierarchies (> 1,000 levels): Driving traversal with an explicit LIFO stack (a last-in, first-out list where the newest pushed tuple is popped next) avoids Python's recursion limit.
  • Digits inside segment names ("a10" vs "a9"): Standard ASCII character-by-character ordering compares '1' against '9', placing "a10" ahead of "a9".

Common mistakes

  • Sorting input strings directly without building a tree: Lists files like "hosts" ahead of folders like "nginx" whenever the file's first letter sorts earlier.
  • Unconditionally assigning current.marked_dir = path.endswith("/"): Overwrites True back to False when "/a/z" arrives after "/a/z/"; only set marked_dir = True when endswith("/") holds.
  • Keeping empty strings from path.split("/"): "/backup/".split("/") yields ["", "backup", ""], inserting phantom "" levels unless filtered out.
  • Pushing ordered children onto the stack in forward order: Because stack.pop() removes from the tail, pushing [first, second] visits second before first; always iterate over reversed(...).
  • Appending a trailing "\n" or indenting with tabs: Stick strictly to " " * depth and "\n".join(lines).

Alternative approaches

  • Recursive pre-order helper: A recursive dfs(node, depth) function is slightly shorter to write when maximum nesting depth is guaranteed to stay well below Python's 1,000-frame call stack.
  • Prefix-tuple key sorting: Extract every prefix tuple ("etc", "nginx", ...) into a set, record which prefixes represent folders, and sort all prefixes by [(0 if prefix[:i] in dirs else 1, prefix[i - 1]) for i in range(1, len(prefix) + 1)]. Python's lexicographical tuple comparison naturally produces pre-order output without explicit node objects, at the expense of repeated prefix comparisons.

Follow-up questions

  • How would you extend the design if each input entry also carried a byte size to display next to files and directories? Accept (path, byte_size) tuples and store byte_size on each file node (overwriting rather than summing if the exact same file path is supplied twice). To also show aggregate folder sizes, run a post-order traversal (a bottom-up pass that computes every child's total before rolling it up into the parent) prior to formatting lines such as "default.conf (512 B)".
  • How would you store and render the hierarchy if billions of paths exceeded available RAM? Persist nodes on disk inside an external B-tree key-value or relational store (a page-oriented disk tree such as RocksDB or SQLite) keyed by (parent_id, is_dir DESC, name ASC). Upserting a child marks its parent's is_dir = 1, and the composite key lets you iterate any folder's immediate children directly from disk in exact display order. During rendering, hold only one active iterator per open depth level on the stack (O(depth) memory) and stream lines directly to an output sink rather than materializing one huge string.
  • How would you add a fast lookup method that finds all full paths matching a target filename? For infrequent queries with zero memory overhead, run the iterative stack traversal while maintaining the current ancestor path segments and record "/" + "/".join(parts) whenever a file node matches (O(N) time). For high-throughput lookups, build an inverted hash index filename_to_paths: Dict[str, List[str]] once the tree is finalized (so nodes promoted to directories by later paths are excluded when searching strictly for files), answering each query in O(1) average lookup time plus the number of matches returned.

Follow-up questions

Similar questions

More Anchorage Digital interview questions

All 3 Anchorage Digital questions →