Bounded In-Memory Directory Tree with Auto-Renaming

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a bounded, case-sensitive in-memory hierarchy of directories and files supporting automatic parent folder creation, per-folder capacity enforcement, OS-style collision numbering, and immediate-child directory listings.

Provide the constant MAX_ENTRIES = 5, custom exception DirectoryFullError(Exception), and class FileSystem:

  • FileSystem(): Initialize an empty root directory.
  • add_file(path: str) -> str: Create any missing intermediate folders along path, store a file at the leaf segment, and return the normalized path assigned to the new file (with no leading "/").
    • Path syntax: Components are separated by "/". One optional leading "/" is accepted and ignored ("/workspace/routes.py" normalizes to "workspace/routes.py"). Any empty segment ("", "/", "a//b", or trailing "dir/") or relative marker (".", "..") raises ValueError.
    • Capacity limit (MAX_ENTRIES = 5): Every folder—including the root—may hold at most 5 immediate entries (files and subfolders combined). Deeper descendants do not count toward an ancestor's limit. If add_file would push any folder past 5 direct entries, raise DirectoryFullError.
    • File-as-folder conflict: If an intermediate segment along path is already a file rather than a directory, raise NotADirectoryError.
    • Atomic failure: Whenever add_file raises ValueError, NotADirectoryError, or DirectoryFullError, the tree and all duplicate counters must remain completely unchanged (no partial intermediate folders created).
    • Collision numbering (non-idempotent): If the leaf name is already used in the target folder by a file or subfolder, rename the new file using the smallest unused integer k >= 1 for that requested name in that folder:
      1. If "." appears at character index > 0, split at the last "." into (stem, ext); otherwise (such as "README" or ".bashrc"), set (stem, ext) = (name, "").
      2. If stem already ends with a parenthesized digit counter (digits) (e.g., "memo (1)"), format candidate k without an extra space as f"{stem}({k}){ext}" (giving "memo (1)(1).md"). Otherwise format with a single space as f"{stem} ({k}){ext}" (giving "memo (1).md").
      3. Track per-name counters per directory while skipping any candidate names already occupied in that directory.
  • get(path: str) -> List[str]: Return the names of all immediate children (files and subfolders) inside directory path, sorted in ascending ASCII/Unicode code-point order.
    • Both "" and "/" denote the root directory.
    • Raise ValueError for malformed paths, FileNotFoundError if path (or an ancestor folder) does not exist, and NotADirectoryError if path (or an ancestor segment) refers to a file.

Examples

Example 1

fs = FileSystem()

fs.add_file("workspace/backend/api/routes.py")
# -> "workspace/backend/api/routes.py"

fs.get("workspace/backend/api")   # -> ["routes.py"]
fs.get("workspace/backend")       # -> ["api"]
fs.get("workspace")               # -> ["backend"]
fs.get("")                        # -> ["workspace"]
fs.get("/")                       # -> ["workspace"]

Walk-through: Adding "workspace/backend/api/routes.py" creates the three nested folders "workspace", "backend", and "api" on the way down. Each get call returns only the direct children at that single level, with both "" and "/" listing the root directory.

Example 2

fs = FileSystem()

fs.add_file("drafts/memo.md")       # -> "drafts/memo.md"
fs.add_file("drafts/memo.md")       # -> "drafts/memo (1).md"
fs.add_file("drafts/memo (1).md")   # -> "drafts/memo (1)(1).md"
fs.add_file("drafts/memo.md")       # -> "drafts/memo (2).md"

fs.get("drafts")
# -> ["memo (1)(1).md", "memo (1).md", "memo (2).md", "memo.md"]

Walk-through: The second "memo.md" gets "memo (1).md". Uploading "memo (1).md" collides with that entry, and because its stem "memo (1)" already ends in (1), the new counter attaches without a space as "memo (1)(1).md". A third "memo.md" advances "memo.md"'s own counter to "memo (2).md". Code-point sorting places '(' (0x28) and ' ' (0x20) ahead of '.' (0x2E).

Example 3

# Continuing with `fs` from Example 2 ("drafts" already holds 4 files):
fs.add_file("drafts/todo.txt")        # -> "drafts/todo.txt" (5th entry in "drafts")
fs.add_file("drafts/sub/extra.txt")   # raises DirectoryFullError ("drafts/sub" is NOT created)
fs.add_file("archive/todo.txt")       # -> "archive/todo.txt" (root now holds "archive" and "drafts")

Walk-through: Once "drafts" reaches 5 direct entries, attempting to add "drafts/sub/extra.txt" would add "sub" as a 6th entry in "drafts", so DirectoryFullError is raised before "sub" is created. Adding under "archive" succeeds because root only has 2 of its 5 slots filled.

Constraints

  • Entry names are case-sensitive ("Notes.txt" and "notes.txt" are distinct entries).
  • Each directory (including root) holds at most MAX_ENTRIES = 5 direct entries (files + subdirectories).
  • Rejected add_file calls must be atomic, leaving all directories, files, and per-name counters untouched.
  • Explain the time and space complexity of add_file and get, both under MAX_ENTRIES = 5 and for general directory size c.

Step-by-step walkthrough

  1. Clarify the rules and edge-case contracts

    Before writing code, establish crisp contracts for every boundary case:

    • Path syntax: paths look like "workspace/backend/api/routes.py", with one optional leading "/" ignored ("/a/b.txt" -> "a/b.txt"). Any empty segment ("", "/" for add_file, "a//b", or trailing slash "dir/") or relative segment (".", "..") raises ValueError.
    • Return value of add_file: returns the normalized final path (such as "drafts/memo (1).md") so the caller knows what name an auto-renamed file received.
    • Not idempotent: calling add_file("drafts/memo.md") twice creates two distinct files ("drafts/memo.md" and "drafts/memo (1).md"), rather than overwriting or ignoring the second call.
    • File vs. folder collisions: if a file already sits where an intermediate folder is required (add_file("a/f.txt/g.txt") when a/f.txt is a file), raise NotADirectoryError. If a leaf file collides with an existing file or folder of the same name (add_file("a") when folder a/ exists), auto-rename the new file ("a (1)").
    • Capacity and atomicity: every directory (including root) holds at most 5 direct entries (files + subfolders). Deeper descendants do not count toward an ancestor's limit. If an add_file call would push any directory past 5 entries, raise DirectoryFullError and create zero intermediate folders.
    • Case sensitivity and get(path): names are case-sensitive ("Memo.md" != "memo.md"). get returns sorted immediate child names ("" and "/" query root), raising FileNotFoundError for missing paths and NotADirectoryError if the target (or an ancestor) is a file.
  2. Model the directory tree in memory

    Represent the hierarchy as a tree of Directory and File nodes. Each Directory stores two small hash maps:

    1. children: maps each immediate entry name to its Directory or File object, making lookup, insertion, and len(children) O(1) on average.
    2. next_suffix: maps each requested base name to the next duplicate counter worth trying (1, 2, ...).
    root Directory("")
      children:
        "drafts"    -> Directory("drafts")
                         children:    {"memo.md": File, "memo (1).md": File}
                         next_suffix: {"memo.md": 2}
        "workspace" -> Directory("workspace")
                         children:    {"backend": Directory("backend")}
                         next_suffix: {}
    
    from typing import Dict, List, Tuple, Union
    import re
    
    MAX_ENTRIES = 5   # files + folders allowed directly inside one directory (the root included)
    
    
    class DirectoryFullError(Exception):
        """The operation would put more than MAX_ENTRIES entries in one directory."""
    
    
    class File:
        def __init__(self, name: str) -> None:
            self.name = name
    
    
    class Directory:
        def __init__(self, name: str) -> None:
            self.name = name
            # children: maps entry_name -> Directory or File, e.g. {"drafts": Directory("drafts")}.
            self.children: Dict[str, Union["Directory", File]] = {}
            # next_suffix: maps requested_name -> next integer >= 1 worth trying on duplicate,
            # e.g. {"memo.md": 2} after "memo (1).md" has been assigned.
            self.next_suffix: Dict[str, int] = {}
    
  3. Parse and validate paths

    Centralize path validation in _split_path so add_file and get enforce identical rules. Stripping at most one leading "/" and then splitting on "/" catches every malformed shape cleanly: "" and "/" become [""], "dir/" becomes ["dir", ""], and "//a" becomes ["", "a"], all of which contain "" and raise ValueError.

    def _split_path(path: str) -> List[str]:
        """Convert '/a/b/c.txt' or 'a/b/c.txt' to ['a', 'b', 'c.txt'], or raise ValueError."""
        # Allow and ignore at most one leading slash; "//a" still leaves an empty part and fails.
        if path.startswith("/"):
            path = path[1:]
        parts = path.split("/")
        # Reject empty segments (from "", "/", "a//b", or trailing "dir/") and "." / "..".
        for part in parts:
            if part in ("", ".", ".."):
                raise ValueError(f"invalid path {path!r}")
        return parts
    
  4. Split extensions and auto-rename duplicates

    OS-style duplicate naming inserts the counter before the file extension ("memo (1).md", not "memo.md (1)"). Find the extension with name.rfind("."):

    • "archive.tar.gz" splits at the last dot into stem "archive.tar" and extension ".gz" -> "archive.tar (1).gz".
    • "README" (dot == -1) and hidden dotfile ".bashrc" (dot == 0) have no extension -> "README (1)" and ".bashrc (1)".
    • If the stem already ends with (digits) (such as "memo (1)"), append ({k}) directly without a space to produce "memo (1)(1).md".

    Never assume next_suffix[name] is automatically free—a user may have added "f (1).txt" manually before duplicating "f.txt". Probe upward with a while loop until an unused name in directory.children is found, then store k + 1:

    def _split_extension(name: str) -> Tuple[str, str]:
        """Split at the last dot: 'a.tar.gz' -> ('a.tar', '.gz'); '.bashrc' -> ('.bashrc', '')."""
        dot = name.rfind(".")
        # dot == -1 means no dot ("README"); dot == 0 means leading-dot hidden file (".bashrc").
        if dot <= 0:
            return name, ""
        return name[:dot], name[dot:]
    
    
    def _numbered(name: str, k: int) -> str:
        """Format duplicate k: 'memo.md' -> 'memo (1).md'; 'memo (1).md' -> 'memo (1)(1).md'."""
        stem, ext = _split_extension(name)
        # If the stem already ends with a "(digits)" suffix, append "(k)" with no extra space.
        if re.search(r"\(\d+\)$", stem):
            return f"{stem}({k}){ext}"
        return f"{stem} ({k}){ext}"
    
    
    def _free_name(directory: Directory, name: str) -> str:
        """Return `name` if unused in `directory`, else the smallest free numbered name."""
        if name not in directory.children:
            return name
        k = directory.next_suffix.get(name, 1)
        # Probe forward in case a numbered name like "f (1).txt" was added manually earlier.
        candidate = _numbered(name, k)
        while candidate in directory.children:
            k += 1
            candidate = _numbered(name, k)
        directory.next_suffix[name] = k + 1
        return candidate
    
  5. Make add_file atomic with a two-phase walk

    If you create missing folders as you walk down "drafts/sub/extra.txt" and only discover partway down—or at the bottom—that "drafts" already has 5 entries, you leave orphan folders behind.

    Look closely at which directory actually gains a child when we add "a/b/new/deep/f.txt" where "a" and "b" already exist:

    Existing folders:   root ---> a ---> b        (ancestors above `b` gain 0 new direct entries!)
                                         |
                                         +---> new (1 entry) ---> deep (1 entry) ---> f.txt
                                         ^
                           `node` = deepest existing folder (`b`):
                           ONLY `b` gains +1 direct entry ("new") in an existing directory!
                           Every newly created folder ("new", "deep") starts at 0 and gets 1 <= 5.
    

    That insight gives a clean three-phase algorithm with zero rollback code needed:

    1. Walk existing folders read-only until the first missing folder (or the bottom of folders), raising NotADirectoryError if an existing entry on the path is a File.
    2. Check capacity once on node: if len(node.children) >= MAX_ENTRIES, raise DirectoryFullError before creating any folder or advancing any next_suffix counter.
    3. Create and insert: build any missing folders, pick final_name = _free_name(node, file_name), and insert File(final_name).
    class FileSystem:
        def __init__(self) -> None:
            self.root = Directory("")
    
        def add_file(self, path: str) -> str:
            parts = _split_path(path)
            folders = parts[:-1]
            file_name = parts[-1]
    
            # Phase 1 (read-only): walk existing folders from root until the first missing folder.
            # Mutating nothing yet guarantees failed calls leave the tree completely untouched.
            node = self.root
            depth = 0
            while depth < len(folders) and folders[depth] in node.children:
                child = node.children[folders[depth]]
                if not isinstance(child, Directory):
                    conflict_path = "/".join(folders[:depth + 1])
                    raise NotADirectoryError(f"{conflict_path} is a file")
                node = child
                depth += 1
    
            # Phase 2 (capacity check): `node` is the ONLY directory that gains an entry in an
            # existing folder—either `folders[depth]` (first missing subfolder) or `final_name`
            # (the new file, even if renamed). Every newly created subfolder below `node` starts
            # empty and receives just 1 entry, so none of them can exceed MAX_ENTRIES (5).
            if len(node.children) >= MAX_ENTRIES:
                where = "/".join(folders[:depth]) or "/"
                raise DirectoryFullError(f"{where} already has {MAX_ENTRIES} entries")
    
            # Phase 3 (mutate): create any missing intermediate folders, then insert the leaf file.
            for name in folders[depth:]:
                new_folder = Directory(name)
                node.children[name] = new_folder
                node = new_folder
            final_name = _free_name(node, file_name)
            node.children[final_name] = File(final_name)
            return "/".join(folders + [final_name])
    
  6. List immediate children with get

    get(path) handles "" and "/" as the root directory, otherwise splits path and walks down one segment at a time. Checking isinstance(node, Directory) both inside the loop (when attempting to traverse through a file, such as get("a/f.txt/sub")) and after the loop (when querying a file directly, such as get("a/f.txt")) raises NotADirectoryError in both cases, while a missing segment raises FileNotFoundError:

        def get(self, path: str) -> List[str]:
            node: Union[Directory, File] = self.root
            # "" and "/" both refer directly to the root directory.
            if path not in ("", "/"):
                for name in _split_path(path):
                    if not isinstance(node, Directory):
                        raise NotADirectoryError(f"{path!r}: {node.name} is a file")
                    if name not in node.children:
                        raise FileNotFoundError(path)
                    node = node.children[name]
            if not isinstance(node, Directory):
                raise NotADirectoryError(f"{path!r} is a file")
            return sorted(node.children)
    
  7. Trace Example 2 and Example 3 step by step

    Walk through the duplicate-renaming sequence and capacity check inside "drafts":

    call                                result                    drafts.children (count) & next_suffix
    ----------------------------------  ------------------------  ---------------------------------------------
    add_file("drafts/memo.md")          "drafts/memo.md"          {"memo.md"} (1)
                                                                  next_suffix={}
    add_file("drafts/memo.md")          "drafts/memo (1).md"      {"memo.md", "memo (1).md"} (2)
                                                                  next_suffix={"memo.md": 2}
    add_file("drafts/memo (1).md")      "drafts/memo (1)(1).md"   {..., "memo (1)(1).md"} (3)
      (stem "memo (1)" ends in "(1)", so no space before "(1)")
                                                                  next_suffix={"memo.md": 2, "memo (1).md": 2}
    add_file("drafts/memo.md")          "drafts/memo (2).md"      {..., "memo (2).md"} (4)
                                                                  next_suffix={"memo.md": 3, "memo (1).md": 2}
    add_file("drafts/todo.txt")         "drafts/todo.txt"         5 entries in drafts (full!)
    add_file("drafts/sub/extra.txt")    DirectoryFullError        still 5 entries; "drafts/sub" is NOT created
    

    Notice how get("drafts") sorts by ASCII code point: '(' (0x28) comes before '.' (0x2E), so "memo (1)(1).md" sorts before "memo (1).md", which sorts before "memo.md".

  8. Complete solution

    from typing import Dict, List, Tuple, Union
    import re
    
    MAX_ENTRIES = 5   # files + folders allowed directly inside one directory (the root included)
    
    
    class DirectoryFullError(Exception):
        """The operation would put more than MAX_ENTRIES entries in one directory."""
    
    
    class File:
        def __init__(self, name: str) -> None:
            self.name = name
    
    
    class Directory:
        def __init__(self, name: str) -> None:
            self.name = name
            # children: maps entry_name -> Directory or File, e.g. {"drafts": Directory("drafts")}.
            self.children: Dict[str, Union["Directory", File]] = {}
            # next_suffix: maps requested_name -> next integer >= 1 worth trying on duplicate,
            # e.g. {"memo.md": 2} after "memo (1).md" has been assigned.
            self.next_suffix: Dict[str, int] = {}
    
    
    def _split_path(path: str) -> List[str]:
        """Convert '/a/b/c.txt' or 'a/b/c.txt' to ['a', 'b', 'c.txt'], or raise ValueError."""
        # Allow and ignore at most one leading slash; "//a" still leaves an empty part and fails.
        if path.startswith("/"):
            path = path[1:]
        parts = path.split("/")
        # Reject empty segments (from "", "/", "a//b", or trailing "dir/") and "." / "..".
        for part in parts:
            if part in ("", ".", ".."):
                raise ValueError(f"invalid path {path!r}")
        return parts
    
    
    def _split_extension(name: str) -> Tuple[str, str]:
        """Split at the last dot: 'a.tar.gz' -> ('a.tar', '.gz'); '.bashrc' -> ('.bashrc', '')."""
        dot = name.rfind(".")
        # dot == -1 means no dot ("README"); dot == 0 means leading-dot hidden file (".bashrc").
        if dot <= 0:
            return name, ""
        return name[:dot], name[dot:]
    
    
    def _numbered(name: str, k: int) -> str:
        """Format duplicate k: 'memo.md' -> 'memo (1).md'; 'memo (1).md' -> 'memo (1)(1).md'."""
        stem, ext = _split_extension(name)
        # If the stem already ends with a "(digits)" suffix, append "(k)" with no extra space.
        if re.search(r"\(\d+\)$", stem):
            return f"{stem}({k}){ext}"
        return f"{stem} ({k}){ext}"
    
    
    def _free_name(directory: Directory, name: str) -> str:
        """Return `name` if unused in `directory`, else the smallest free numbered name."""
        if name not in directory.children:
            return name
        k = directory.next_suffix.get(name, 1)
        # Probe forward in case a numbered name like "f (1).txt" was added manually earlier.
        candidate = _numbered(name, k)
        while candidate in directory.children:
            k += 1
            candidate = _numbered(name, k)
        directory.next_suffix[name] = k + 1
        return candidate
    
    
    class FileSystem:
        def __init__(self) -> None:
            self.root = Directory("")
    
        def add_file(self, path: str) -> str:
            parts = _split_path(path)
            folders = parts[:-1]
            file_name = parts[-1]
    
            # Phase 1 (read-only): walk existing folders from root until the first missing folder.
            # Mutating nothing yet guarantees failed calls leave the tree completely untouched.
            node = self.root
            depth = 0
            while depth < len(folders) and folders[depth] in node.children:
                child = node.children[folders[depth]]
                if not isinstance(child, Directory):
                    conflict_path = "/".join(folders[:depth + 1])
                    raise NotADirectoryError(f"{conflict_path} is a file")
                node = child
                depth += 1
    
            # Phase 2 (capacity check): `node` is the ONLY directory that gains an entry in an
            # existing folder—either `folders[depth]` (first missing subfolder) or `final_name`
            # (the new file, even if renamed). Every newly created subfolder below `node` starts
            # empty and receives just 1 entry, so none of them can exceed MAX_ENTRIES (5).
            if len(node.children) >= MAX_ENTRIES:
                where = "/".join(folders[:depth]) or "/"
                raise DirectoryFullError(f"{where} already has {MAX_ENTRIES} entries")
    
            # Phase 3 (mutate): create any missing intermediate folders, then insert the leaf file.
            for name in folders[depth:]:
                new_folder = Directory(name)
                node.children[name] = new_folder
                node = new_folder
            final_name = _free_name(node, file_name)
            node.children[final_name] = File(final_name)
            return "/".join(folders + [final_name])
    
        def get(self, path: str) -> List[str]:
            node: Union[Directory, File] = self.root
            # "" and "/" both refer directly to the root directory.
            if path not in ("", "/"):
                for name in _split_path(path):
                    if not isinstance(node, Directory):
                        raise NotADirectoryError(f"{path!r}: {node.name} is a file")
                    if name not in node.children:
                        raise FileNotFoundError(path)
                    node = node.children[name]
            if not isinstance(node, Directory):
                raise NotADirectoryError(f"{path!r} is a file")
            return sorted(node.children)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a tree of office filing cabinets where every folder drawer can hold at most 5 direct items (either subfolders or paper files), and dropping a duplicate "memo.md" into a drawer automatically clips a numbered tag ("memo (1).md", "memo (2).md") onto the new sheet just like your laptop's Downloads folder. Before creating any new nested drawers for a deep path like "drafts/sub/extra.txt", we first walk down the drawers that already exist ("drafts") and check whether that deepest existing drawer has an open slot—because "drafts" is the only existing drawer that will gain a new item ("sub"), whereas any newly created drawers start empty and receive just 1 item each.

Two naive shortcuts break right away. If you create missing folders eagerly while walking down the path and only check capacity at the leaf (or fail halfway down), a rejected operation leaves empty orphan folders or a 6-item parent behind; and if you blindly trust a per-name counter without checking whether "memo (1).md" was already created by hand, you silently overwrite an existing file.

Instead, we model the hierarchy as an n-ary tree (a tree where each directory node maps child names to child nodes via a hash dictionary), validate the existing prefix before mutating anything to preserve atomicity (either the entire operation succeeds or zero state changes), and keep a next_suffix counter per base name in each directory that probes past any already-taken names. Walk through Example 2 inside "drafts/":

  1. add_file("drafts/memo.md"): "drafts" is created at root (1/5 entries); "memo.md" is free -> "drafts/memo.md".
  2. add_file("drafts/memo.md"): "memo.md" is taken; counter starts at 1, "memo (1).md" is free, next_suffix["memo.md"] becomes 2 -> "drafts/memo (1).md".
  3. add_file("drafts/memo (1).md"): "memo (1).md" is taken; its stem "memo (1)" already ends in (1), so (1) is appended without a space -> "drafts/memo (1)(1).md".
  4. add_file("drafts/memo.md"): resumes from next_suffix["memo.md"] == 2 -> "drafts/memo (2).md".

Complexity

Let P be the length of the input path string in characters.

  • add_file(path): O(P) average time. Splitting and validating path scans its P characters once; walking existing folders and creating missing folders hashes each path component once (O(P) total characters hashed); checking len(node.children) >= 5 is O(1); and _free_name probes at most 4 candidate names because node holds at most 4 entries before insertion.
  • get(path): O(P) average time with MAX_ENTRIES = 5. Walking the path hashes at most P characters across O(1)-average dictionary lookups, and sorting at most 5 child strings takes a constant number of string comparisons.
  • Space: O(total characters across all stored file and folder names), because each created Directory and File node stores its name once, plus at most one integer in next_suffix per duplicated base name.
  • Scaling without the 5-entry cap: if a directory can hold c entries, get takes O(P + c log c) time to sort the c child names, and next_suffix keeps duplicate insertion fast in amortized time (average work per call across a long sequence of calls) because next_suffix[name] only moves forward and skips each manually pre-created "name (k)" entry at most once.

Edge cases

  • Capacity applies to every directory, including root: once root holds 5 entries, add_file("sixth_folder/a.txt") raises DirectoryFullError, whereas add_file("existing_folder/a.txt") still succeeds if "existing_folder" has fewer than 5 entries.
  • Duplicates still consume a slot: calling add_file("d/f0.txt") when "d" already has 5 entries raises DirectoryFullError before _free_name runs, so next_suffix is not incremented.
  • File vs. folder collisions: traversing through an existing file ("a/f.txt/g.txt") raises NotADirectoryError, whereas adding a leaf file whose name matches an existing subfolder (add_file("a") when folder "a" exists) renames the new file to "a (1)".
  • Pre-existing numbered files: if "f (1).txt" was added before duplicating "f.txt", _free_name sees "f (1).txt" in children and skips cleanly to "f (2).txt".
  • Extension splitting rules: "archive.tar.gz" splits at the last dot ("archive.tar (1).gz"), while ".bashrc" (leading dot) and "README" (no dot) have empty extensions (".bashrc (1)", "README (1)").
  • Non-idempotent adds and case sensitivity: idempotency means repeating the exact same call has no extra effect; here add_file is intentionally not idempotent because duplicates auto-rename, and "Memo.md" and "memo.md" coexist as distinct entries.

Common mistakes

  • Mutating the tree during the downward walk: creating "drafts/sub" before discovering a conflict or capacity error leaves stray empty folders behind.
  • Checking capacity only on the leaf folder: adding "drafts/sub/extra.txt" inserts "sub" into "drafts", which overflows "drafts" if "drafts" already had 5 entries.
  • Advancing next_suffix before checking capacity: a rejected duplicate call on a full folder then causes a gap in numbering if a slot is later freed.
  • Trusting next_suffix without checking directory.children: overwrites "f (1).txt" if a user uploaded "f (1).txt" directly earlier.
  • Splitting at the first dot or treating dotfiles as pure extensions: name.split(".")[0] turns "archive.tar.gz" into "archive (1).tar.gz" and turns ".bashrc" into " (1).bashrc".
  • Checking duplicates against files only: forgets that a file and a subfolder cannot share the exact same key inside one directory.

Alternative approaches

  • Flat dictionary of full paths ({"a/b/c.txt": "file"}): simple to write for tiny tests (we use it as _BruteFS in tests.py), but every get and every capacity check must scan all stored paths in the entire file system instead of inspecting one directory dictionary in O(1).
  • Probing from k = 1 on every duplicate without next_suffix: completely fine when MAX_ENTRIES = 5 (at most 4 checks), though keeping next_suffix avoids O(c) rescanning per add if MAX_ENTRIES is later raised to thousands of files.

Follow-up questions

  • How should deleting a file or empty directory affect the 5-entry limit and the per-name duplicate counters? Removing a file or empty folder deletes its key from parent.children, immediately freeing one of the 5 capacity slots in that parent directory. For numbering, there are two valid product policies: either leave next_suffix untouched so historical numbers are never reused (preventing confusion with old filenames), or parse a deleted "stem (k).ext" and set next_suffix[base] = min(next_suffix[base], k) so future duplicates fill the lowest freed number while the while candidate in children loop still skips higher taken numbers.
  • What changes are needed to enforce case-insensitive collision checks while still displaying each entry's original casing? Key Directory.children and Directory.next_suffix by name.casefold() while storing the original casing on child.name. Lookups and duplicate checks then treat "Memo.md" and "memo.md" as the same slot (renaming the second to "Memo (1).md"), while get(path) returns [child.name for child in ...] sorted in the desired order.
  • How would you make concurrent add_file and get calls thread-safe without risking deadlocks or exceeding directory capacity? Checking len(node.children) < 5, choosing a free duplicate name, and inserting into node.children must happen atomically; the simplest design guards add_file and get with a single threading.RLock. For higher concurrency across disjoint subtrees, place a lock on each Directory and always acquire locks top-down from parent to child so two threads can never deadlock (freeze forever because Thread A holds lock X waiting for Y while Thread B holds Y waiting for X), re-checking under node's lock whether another thread just created folders[depth] in the meantime.

Follow-up questions

Similar questions

More Harvey interview questions

All 46 Harvey questions →