Hierarchical File Vault with Numbered Collision Resolution

Hard · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Design an in-memory directory tree rooted at "/" that stores files, creates missing parent folders on demand, lists immediate folder contents in ASCII order, and resolves filename collisions by inserting the lowest unused positive number before the file extension.

Implement both the helper function split_name and the FileVault class:

  • split_name(name: str) -> Tuple[str, str]: Partition a single filename into (base, ext):
    1. Locate the rightmost dot "." in name. If its index is strictly greater than 0, base is the prefix before that dot and ext is everything from that dot to the end (for instance, "bundle.tar.xz" splits into ("bundle.tar", ".xz"), and ".env.prod" splits into (".env", ".prod")).
    2. If name contains no dot, or its only dot sits at index 0 (such as "Makefile" or ".gitignore"), base is name itself and ext is "".
  • FileVault(): Create a new vault containing only an empty root folder "/".
  • add_file(path: str) -> str: Store a file at the absolute path path and return the final absolute path assigned to it:
    • Create any ancestor folders along path that do not exist yet.
    • Raise ValueError (leaving the vault unchanged) if path does not start with "/", if path == "/", or if any ancestor segment along path is already an existing file.
    • If the requested leaf filename is not yet used by any file or subfolder inside the destination folder, store it under that exact name. Otherwise, split the requested leaf name into (base, ext) via split_name and try candidate names f"{base} ({k}){ext}" for k = 1, 2, 3, ..., picking the smallest k >= 1 not yet occupied by a file or subfolder in that folder. Existing numeric suffixes in a requested name are treated as ordinary characters of base (duplicating "draft (1).md" produces "draft (1) (1).md").
  • list_dir(path: str) -> List[str]: Return a list of immediate child names (both files and subfolders) directly inside path, ordered by ASCII code point. Return [] when path does not exist, does not begin with "/", or points to (or through) a file.

Examples

Example 1

vault = FileVault()

vault.add_file("/projects/q4/budget.csv")   # -> "/projects/q4/budget.csv"
vault.add_file("/projects/q4/budget.csv")   # -> "/projects/q4/budget (1).csv"
vault.add_file("/projects/q4/budget.csv")   # -> "/projects/q4/budget (2).csv"
vault.add_file("/projects/roadmap.md")      # -> "/projects/roadmap.md"

vault.list_dir("/projects")
# -> ["q4", "roadmap.md"]

vault.list_dir("/projects/q4")
# -> ["budget (1).csv", "budget (2).csv", "budget.csv"]

Walk-through: Adding "/projects/q4/budget.csv" creates /projects and /projects/q4 automatically. The next two uploads of the same path collide with existing names in /projects/q4 and receive suffixes (1) and (2) before ".csv". In list_dir("/projects/q4"), space ' ' (ASCII 32) sorts ahead of dot '.' (ASCII 46), so "budget (1).csv" and "budget (2).csv" precede "budget.csv".

Example 2

vault = FileVault()

vault.add_file("/srv/.gitignore")      # -> "/srv/.gitignore"
vault.add_file("/srv/.gitignore")      # -> "/srv/.gitignore (1)"
vault.add_file("/srv/spec (2).md")     # -> "/srv/spec (2).md"
vault.add_file("/srv/spec.md")         # -> "/srv/spec.md"
vault.add_file("/srv/spec.md")         # -> "/srv/spec (1).md"
vault.add_file("/srv/spec.md")         # -> "/srv/spec (3).md"

vault.list_dir("/srv")
# -> [".gitignore", ".gitignore (1)", "spec (1).md", "spec (2).md", "spec (3).md", "spec.md"]

Walk-through: Because ".gitignore" has its only dot at index 0, its extension is "" and its duplicate becomes ".gitignore (1)". Uploading "spec (2).md" claims that exact name directly; later collisions on "spec.md" first take the lowest open suffix k = 1 ("spec (1).md") and then skip the already-occupied "spec (2).md" to land on k = 3 ("spec (3).md").

Constraints

  • Valid query and file paths are absolute ASCII strings starting with "/", with no consecutive slashes ("//"), no / inside individual segment names, and no trailing slash other than root "/" itself.
  • Within any single directory, a file and a subdirectory never share the exact same name; candidate collision suffixes must also skip names already held by subdirectories.
  • At most 10,000 combined calls will be made to add_file and list_dir.

Step-by-step walkthrough

  1. Model the vault as a directory tree

    We need an in-memory file hierarchy rooted at "/" with two operations: - add_file(path) walks down from "/", creates any missing parent folders, picks the smallest unused (k) suffix if the filename is already occupied in that folder, and returns the final absolute path. - list_dir(path) returns all immediate child names (both files and subfolders) inside path in ASCII order, or [] if path does not exist or points to a file.

    Instead of storing flat strings like "/projects/q4/budget.csv" in one giant set (which would force list_dir to scan the entire vault), we model the hierarchy as a tree of Directory nodes — essentially a trie keyed by path segments:

    root ("/")
      |-- dirs["projects"] --> Directory
      |                          |-- dirs["q4"] --> Directory
      |                          |                    |-- files = {"budget.csv", "budget (1).csv"}
      |                          |                    |-- sorted_names = ["budget (1).csv", "budget.csv"]
      |                          |                    +-- next_suffix = {("budget", ".csv"): 2}
      |                          |-- files = {"roadmap.md"}
      |                          +-- sorted_names = ["q4", "roadmap.md"]
      +-- dirs["srv"] -------> Directory
                                 |-- files = {".gitignore"}
                                 +-- sorted_names = [".gitignore"]
    

    Each Directory node stores only its immediate children: 1. dirs: maps child directory name to its Directory object so we can step down a path one segment at a time. 2. files: a set of immediate file names for O(1) collision checks. 3. sorted_names: an ASCII-sorted list of all child names (both directories and files) maintained via bisect.insort so list_dir never has to re-sort from scratch. 4. next_suffix: a cache mapping (base, ext) to the next k to try on duplicate filenames (we will see in Step 4 why this turns a quadratic bottleneck into O(1) amortized checks!).

    Note two clean boundary rules: - A file and a directory cannot share a name in the same parent, so has_entry(name) checks both self.dirs and self.files. If a subdirectory named "x (1).txt" exists, duplicating "x.txt" skips 1 and picks "x (2).txt". - Passing a path whose parent segment is an existing file (e.g. add_file("/d/f.txt/g.txt") after creating file /d/f.txt) raises ValueError.

    class Directory:
        def __init__(self) -> None:
            # self.dirs: {"projects": Directory(...)} maps immediate subdirectory name -> child node
            self.dirs: Dict[str, "Directory"] = {}
            # self.files: {"budget.csv", "budget (1).csv"} stores immediate file names for O(1) lookup
            self.files: Set[str] = set()
            # self.sorted_names: ["budget (1).csv", "budget.csv", "q4"] maintains ASCII-sorted children
            self.sorted_names: List[str] = []
            # self.next_suffix: {("budget", ".csv"): 2} caches the smallest k >= 1 not yet confirmed taken.
            # Because entries are never deleted, every suffix < next_suffix stays taken permanently.
            self.next_suffix: Dict[Tuple[str, str], int] = {}
    
        def has_entry(self, name: str) -> bool:
            return name in self.dirs or name in self.files
    
        def add_subdir(self, name: str) -> "Directory":
            child = Directory()
            self.dirs[name] = child
            bisect.insort(self.sorted_names, name)
            return child
    
        def add_file_entry(self, name: str) -> None:
            self.files.add(name)
            bisect.insort(self.sorted_names, name)
    
  2. Split filenames into base and extension

    When "budget.csv" collides, the (k) suffix must go before the extension ("budget (1).csv"), not at the very end. Let's check the exact extension rules: 1. Find the last . in name using name.rfind("."). 2. If dot_index > 0, base is name[:dot_index] and ext is name[dot_index:] (including the dot). 3. Otherwise — either there is no dot (dot_index == -1) or the only dot is at index 0 (dot_index == 0, like ".gitignore") — ext is "" and base is the entire name!

    filename            rfind(".")   base             ext        k = 1 candidate
    ------------------  ----------   --------------   --------   ---------------------
    "bundle.tar.xz"         10       "bundle.tar"     ".xz"      "bundle.tar (1).xz"
    ".gitignore"             0       ".gitignore"     ""         ".gitignore (1)"
    ".env.prod"              4       ".env"           ".prod"    ".env (1).prod"
    "Makefile"              -1       "Makefile"       ""         "Makefile (1)"
    "archive."               7       "archive"        "."        "archive (1)."
    "draft (1).md"           9       "draft (1)"      ".md"      "draft (1) (1).md"
    

    Notice that last row: if the caller explicitly passes add_file("/draft (1).md") twice, its base is literally "draft (1)", so its duplicate becomes "/draft (1) (1).md" — we never strip an existing (1).

    def split_name(name: str) -> Tuple[str, str]:
        # `rfind(".")` returns -1 if "." is absent and 0 if "." is only at the very start (e.g. ".env").
        # Requiring `dot_index > 0` handles both rules at once: dotfiles and dotless names get ext == "".
        dot_index = name.rfind(".")
        if dot_index > 0:
            return name[:dot_index], name[dot_index:]
        return name, ""
    
  3. Walk parent directories and auto-create missing ones

    Splitting "/projects/q4/budget.csv" on "/" produces ["", "projects", "q4", "budget.csv"]. Slicing [1:] drops the empty string before the leading "/", leaving: - parent_names = ["projects", "q4"] - target_name = "budget.csv"

    We start node = self.root and step through parent_names: - If dir_name in node.files, a file blocks the directory path, so we raise ValueError. Notice why this never leaves half-created directories behind: node.files can only be non-empty on directories that already existed before this call! Once we call node.add_subdir(...) for the first missing directory, every deeper directory is brand-new and has an empty files set, so ValueError can never fire after we mutate the tree. - Otherwise we step into node.dirs[dir_name] or create it with node.add_subdir(dir_name).

    class FileVault:
        def __init__(self) -> None:
            self.root = Directory()
    
        def add_file(self, path: str) -> str:
            if not path.startswith("/") or path == "/":
                raise ValueError(f"expected a file path inside '/', got {path!r}")
    
            # "/projects/q4/budget.csv".split("/")[1:] -> ["projects", "q4", "budget.csv"]
            parts = path.split("/")[1:]
            parent_names = parts[:-1]
            target_name = parts[-1]
    
            # Phase 1: walk parent directories, creating missing ones on the way down.
            # `name in node.files` can only trigger on pre-existing nodes before any new directory
            # is created, so a raised ValueError never leaves half-created directories behind.
            node = self.root
            for dir_name in parent_names:
                if dir_name in node.files:
                    raise ValueError(f"{dir_name!r} is an existing file, not a directory")
                if dir_name in node.dirs:
                    node = node.dirs[dir_name]
                else:
                    node = node.add_subdir(dir_name)
    
            # Phase 2: resolve any name collision inside `node` and insert the winning filename.
            final_name = self._resolve_free_name(node, target_name)
            node.add_file_entry(final_name)
            return "/" + "/".join(parent_names + [final_name])
    
  4. Resolve duplicate names in amortized O(1) time

    What happens if we naively check k = 1, 2, 3, ... from 1 on every single collision? If a caller adds "/d/a.txt" 10,000 times (the operation limit): - The 2nd call checks k = 1 (1 check). - The 3rd call checks k = 1, 2 (2 checks). - The 10,000th call checks k = 1 .. 9,999 (9,999 checks). In total, 1 + 2 + ... + 9,999 ≈ 50,000,000 string builds and set lookups — several seconds for one test!

    Now notice a crucial invariant: entries in FileVault are never deleted. Once we verify that k = 1 .. m are all taken in node for (base, ext), they remain taken forever! So we store node.next_suffix[(base, ext)] = k + 1 after assigning suffix k, and start the next collision search for (base, ext) right at node.next_suffix[(base, ext)]:

    1. add_file("/srv/spec (2).md") -> "spec (2).md" is free! Added directly.
                                       (next_suffix is still empty)
    2. add_file("/srv/spec.md")     -> "spec.md" is free! Added directly.
    3. add_file("/srv/spec.md")     -> collision! key = ("spec", ".md"), start k = 1:
                                       "spec (1).md" is free! Assign k = 1, save next_suffix = 2.
    4. add_file("/srv/spec.md")     -> collision! resume at k = 2:
                                       "spec (2).md" is TAKEN -> k becomes 3
                                       "spec (3).md" is free! Assign k = 3, save next_suffix = 4.
    

    Every increment of k inside the while loop permanently skips an existing entry for that (base, ext) key, so 10,000 duplicate adds perform only ~10,000 checks total instead of 50 million!

        def _resolve_free_name(self, node: Directory, name: str) -> str:
            # If the exact requested name is unused, take it without touching the suffix cache.
            if not node.has_entry(name):
                return name
    
            base, ext = split_name(name)
            key = (base, ext)
            k = node.next_suffix.get(key, 1)
            while node.has_entry(f"{base} ({k}){ext}"):
                k += 1
    
            # Record k + 1 because `f"{base} ({k}){ext}"` is about to be inserted right now.
            node.next_suffix[key] = k + 1
            return f"{base} ({k}){ext}"
    
  5. List directory contents in ASCII order

    To implement list_dir(path): 1. Handle "/" explicitly ("/".split("/") is ["", ""], whereas root corresponds to self.root with zero directory hops). 2. Walk path.split("/")[1:] through node.dirs only. If a segment is missing — or is a file in node.files rather than a directory in node.dirs — return []. 3. Return list(node.sorted_names) (a fresh shallow copy so a caller who runs result.append(...) cannot corrupt the vault!).

    Why does "spec (1).md" appear before "spec.md" in Example 2? Because Python compares strings by Unicode/ASCII code point, and space ' ' (ASCII 32) comes before dot '.' (ASCII 46)! Keeping sorted_names sorted on each insertion via bisect.insort makes every list_dir a fast O(L + c) slice copy instead of an O(c log c) sort.

        def list_dir(self, path: str) -> List[str]:
            node = self._find_dir(path)
            if node is None:
                return []
            # Return a shallow copy so caller mutations cannot corrupt `node.sorted_names`.
            return list(node.sorted_names)
    
        def _find_dir(self, path: str) -> Optional[Directory]:
            if not path.startswith("/"):
                return None
            if path == "/":
                return self.root
    
            node = self.root
            for dir_name in path.split("/")[1:]:
                if dir_name not in node.dirs:
                    return None
                node = node.dirs[dir_name]
            return node
    
  6. Trace Example 2 step by step

    Let's watch /srv's internal state across every call of Example 2:

    Call                              Returned path          next_suffix in /srv                sorted_names in /srv
    --------------------------------  ---------------------  ---------------------------------  ------------------------------------------------------------------
    add_file("/srv/.gitignore")       "/srv/.gitignore"      {}                                 [".gitignore"]
    add_file("/srv/.gitignore")       "/srv/.gitignore (1)"  {(".gitignore", ""): 2}            [".gitignore", ".gitignore (1)"]
    add_file("/srv/spec (2).md")      "/srv/spec (2).md"     {(".gitignore", ""): 2}            [".gitignore", ".gitignore (1)", "spec (2).md"]
    add_file("/srv/spec.md")          "/srv/spec.md"         {(".gitignore", ""): 2}            [".gitignore", ".gitignore (1)", "spec (2).md", "spec.md"]
    add_file("/srv/spec.md")          "/srv/spec (1).md"     {(".gitignore", ""): 2,            [".gitignore", ".gitignore (1)", "spec (1).md",
                                                              ("spec", ".md"): 2}                "spec (2).md", "spec.md"]
    add_file("/srv/spec.md")          "/srv/spec (3).md"     {(".gitignore", ""): 2,            [".gitignore", ".gitignore (1)", "spec (1).md",
                                                              ("spec", ".md"): 4}                "spec (2).md", "spec (3).md", "spec.md"]
    list_dir("/srv")                  -> [".gitignore", ".gitignore (1)", "spec (1).md", "spec (2).md", "spec (3).md", "spec.md"]
    
  7. Complete solution

    from typing import Dict, List, Optional, Set, Tuple
    import bisect
    
    
    def split_name(name: str) -> Tuple[str, str]:
        # `rfind(".")` returns -1 if "." is absent and 0 if "." is only at the very start (e.g. ".env").
        # Requiring `dot_index > 0` handles both rules at once: dotfiles and dotless names get ext == "".
        dot_index = name.rfind(".")
        if dot_index > 0:
            return name[:dot_index], name[dot_index:]
        return name, ""
    
    
    class Directory:
        def __init__(self) -> None:
            # self.dirs: {"projects": Directory(...)} maps immediate subdirectory name -> child node
            self.dirs: Dict[str, "Directory"] = {}
            # self.files: {"budget.csv", "budget (1).csv"} stores immediate file names for O(1) lookup
            self.files: Set[str] = set()
            # self.sorted_names: ["budget (1).csv", "budget.csv", "q4"] maintains ASCII-sorted children
            self.sorted_names: List[str] = []
            # self.next_suffix: {("budget", ".csv"): 2} caches the smallest k >= 1 not yet confirmed taken.
            # Because entries are never deleted, every suffix < next_suffix stays taken permanently.
            self.next_suffix: Dict[Tuple[str, str], int] = {}
    
        def has_entry(self, name: str) -> bool:
            return name in self.dirs or name in self.files
    
        def add_subdir(self, name: str) -> "Directory":
            child = Directory()
            self.dirs[name] = child
            bisect.insort(self.sorted_names, name)
            return child
    
        def add_file_entry(self, name: str) -> None:
            self.files.add(name)
            bisect.insort(self.sorted_names, name)
    
    
    class FileVault:
        def __init__(self) -> None:
            self.root = Directory()
    
        def add_file(self, path: str) -> str:
            if not path.startswith("/") or path == "/":
                raise ValueError(f"expected a file path inside '/', got {path!r}")
    
            # "/projects/q4/budget.csv".split("/")[1:] -> ["projects", "q4", "budget.csv"]
            parts = path.split("/")[1:]
            parent_names = parts[:-1]
            target_name = parts[-1]
    
            # Phase 1: walk parent directories, creating missing ones on the way down.
            # `name in node.files` can only trigger on pre-existing nodes before any new directory
            # is created, so a raised ValueError never leaves half-created directories behind.
            node = self.root
            for dir_name in parent_names:
                if dir_name in node.files:
                    raise ValueError(f"{dir_name!r} is an existing file, not a directory")
                if dir_name in node.dirs:
                    node = node.dirs[dir_name]
                else:
                    node = node.add_subdir(dir_name)
    
            # Phase 2: resolve any name collision inside `node` and insert the winning filename.
            final_name = self._resolve_free_name(node, target_name)
            node.add_file_entry(final_name)
            return "/" + "/".join(parent_names + [final_name])
    
        def _resolve_free_name(self, node: Directory, name: str) -> str:
            # If the exact requested name is unused, take it without touching the suffix cache.
            if not node.has_entry(name):
                return name
    
            base, ext = split_name(name)
            key = (base, ext)
            k = node.next_suffix.get(key, 1)
            while node.has_entry(f"{base} ({k}){ext}"):
                k += 1
    
            # Record k + 1 because `f"{base} ({k}){ext}"` is about to be inserted right now.
            node.next_suffix[key] = k + 1
            return f"{base} ({k}){ext}"
    
        def list_dir(self, path: str) -> List[str]:
            node = self._find_dir(path)
            if node is None:
                return []
            # Return a shallow copy so caller mutations cannot corrupt `node.sorted_names`.
            return list(node.sorted_names)
    
        def _find_dir(self, path: str) -> Optional[Directory]:
            if not path.startswith("/"):
                return None
            if path == "/":
                return self.root
    
            node = self.root
            for dir_name in path.split("/")[1:]:
                if dir_name not in node.dirs:
                    return None
                node = node.dirs[dir_name]
            return node
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the vault as a real cabinet of nested folders where each folder keeps two things taped inside its cover: an alphabetical index card of the items directly inside it, and a sticky note remembering where it left off numbering duplicates (like "budget.csv -> try (3) next"). In computer science, this nested folder structure is a trie (a tree where each step down an edge matches one segment of a path or prefix).

Two naive shortcuts break down fast here. First, storing full paths like "/projects/q4/budget.csv" in one flat set forces list_dir("/projects/q4") to scan every file in the entire vault instead of just /projects/q4. Second, restarting the duplicate search at k = 1 on every collision turns 10,000 uploads of "a.txt" into 1 + 2 + ... + 9,999 ≈ 50,000,000 hash lookups; conversely, blindly incrementing a counter without checking existing filenames fails when a user uploaded "spec (2).md" manually before "spec.md".

Walk through Example 2 inside /srv: 1. add_file("/srv/.gitignore"): /srv does not exist yet, so root creates Directory("srv") and inserts ".gitignore". Adding "/srv/.gitignore" a second time sees ".gitignore" is taken; because the only dot is at index 0, split_name treats the whole string ".gitignore" as the base with extension "", picks ".gitignore (1)", and saves next_suffix[(".gitignore", "")] = 2. 2. add_file("/srv/spec (2).md") followed by add_file("/srv/spec.md"): both exact names are free, so both are inserted as-is without touching next_suffix. 3. Two more add_file("/srv/spec.md") calls: the first collision starts at k = 1, sees "spec (1).md" is free, inserts it, and sets next_suffix[("spec", ".md")] = 2; the next collision starts at k = 2, sees "spec (2).md" is already in files, advances to k = 3, inserts "spec (3).md", and sets next_suffix = 4.

Complexity

Let L be the character length of path, m be the length of the target filename, and c be the number of immediate entries inside the target directory:

  • add_file(path): O(L + m + c) amortized time (average cost per operation guaranteed over any worst-case sequence of calls). Splitting and walking path hashes each segment once in O(L) time. Because files are never deleted, next_suffix never moves backward: each stored entry in the directory can be skipped by the while loop at most once across the entire run, giving O(1) amortized candidate checks (each costing O(m) to format and hash). Finally, binary search insertion (bisect.insort, which finds the sorted position in O(log c) comparisons and shifts up to c list pointers) takes O(c) time.
  • list_dir(path): O(L + c) time. Walking path from the root inspects O(L) characters, and copying the pre-sorted sorted_names list copies c string references without sorting.
  • Space: O(total characters across all unique directory and file names). Each directory and file name is stored once in its parent's hash table/set and once by reference in sorted_names, plus at most one (base, ext) entry in next_suffix per colliding name family.

Edge cases

  • Leading-dot hidden files (".env", ".gitignore"): When the only dot sits at index 0, rfind(".") returns 0 (not > 0), so ext is "" and the duplicate is ".gitignore (1)", never " (1).gitignore".
  • Multi-dot and trailing-dot names: "bundle.tar.xz" splits at the last dot into ("bundle.tar", ".xz") -> "bundle.tar (1).xz", while ".env.prod" has its last dot at index 4 > 0 and splits into (".env", ".prod") -> ".env (1).prod", and "x." splits into ("x", ".") -> "x (1).".
  • Names already ending in (k): Adding "/r (1).pdf" twice treats "r (1)" as the base and produces "/r (1) (1).pdf", whereas adding "/r.pdf" twice afterwards skips "r (1).pdf" and produces "/r (2).pdf".
  • Collision with an existing subdirectory name: If /projects/x (1).txt was created as a directory, node.has_entry("x (1).txt") returns True, so duplicating /projects/x.txt safely skips 1 and assigns /projects/x (2).txt.
  • ASCII sorting quirks (list_dir): Lexicographical ASCII order (comparing strings character by character using their numeric 0–127 ASCII codes) orders ' ' (32) < '.' (46) < '0'–'9' (48–57) < 'A'–'Z' (65–90) < '_' (95) < 'a'–'z' (97–122), which is why "spec (1).md" sorts before "spec.md" and "B.txt" sorts before "a.txt".
  • Root, missing, or file paths in list_dir: list_dir("/") lists root's children, while list_dir("/unknown") and list_dir("/projects/roadmap.md") both return [].

Common mistakes

  • Splitting on the first dot (name.find(".")) or on dot >= 0: find(".") turns "bundle.tar.xz" into "bundle (1).tar.xz", and dot >= 0 turns ".gitignore" into " (1).gitignore".
  • Restarting k = 1 from scratch on every collision: Repeatedly adding the same filename N times performs N * (N - 1) / 2 hash lookups, timing out at N = 10,000.
  • Using a blind counter without checking node.has_entry(...): Handing out k = 1, 2, ... without checking whether "spec (2).md" was already added manually overwrites an existing file.
  • Checking name in node.files instead of name in node.files or name in node.dirs: Allows a newly suffixed file to collide with an existing subdirectory of the same name.
  • Forgetting path == "/" when splitting on "/": "/".split("/")[1:] evaluates to [""] instead of [], looking up a nonexistent "" child directory unless "/" is handled explicitly.
  • Returning node.sorted_names directly instead of list(node.sorted_names): Exposes internal state so caller mutations corrupt future directory listings.

Alternative approaches

  • Balanced search tree per directory (e.g. sortedcontainers.SortedList or a B-tree): If a single directory held millions of entries instead of 10,000, replacing the plain list + bisect.insort (which shifts O(c) pointers in C) with a balanced tree makes both insertion and ordered iteration strictly O(log c) / O(c).
  • Sort lazily on list_dir with a dirty flag: Append new names to a plain list in O(1) and mark node.dirty = True, sorting node.sorted_names only when list_dir sees node.dirty == True. This speeds up write-only workloads while keeping repeated list_dir calls O(c).

Follow-up questions

  • How can you avoid scanning from k = 1 every time when a single filename is uploaded millions of times, and what changes if deletions are also allowed? Our next_suffix[(base, ext)] pointer already solves the append-only case in O(1) amortized time per upload because no k below next_suffix can ever become free again. Once delete_file is allowed, deleted suffixes below next_suffix open up reusable gaps; to keep both uploads and deletions at O(log D) time without scanning from 1, pair next_suffix[(base, ext)] (the high-water mark) with a per-key min-heap (a priority queue that pops the smallest available number in O(log D) time) of freed k values, popping from the min-heap first whenever it holds a free k < next_suffix.

  • What adjustments are needed to support fast directory moves or renames (such as moving /src to /archive/src) without rewriting every descendant path? Because Directory nodes store only local child names rather than full path strings, moving /src (even with a million nested files underneath) only unlinks "src" from its old parent's dirs and sorted_names, resolves any name collision in /archive, and attaches the existing Directory pointer there in O(depth + c) time. Add a parent pointer on each Directory so the move can walk upward from /archive to verify you are not moving /src inside /src/sub (which would detach a cycle from root), and invalidate or update the old parent's next_suffix entry for (base, ext) when a suffixed entry moves out.

  • How would you allow concurrent reads and writes across the vault without serializing every thread behind one global lock? Give each Directory node its own reader-writer lock (a lock allowing either many concurrent readers or one exclusive writer on that single directory) and walk paths with hand-over-hand locking: traversing /projects/q4/budget.csv locks root just long enough to fetch or create projects, locks projects before releasing root, and holds the write lock on q4 across both _resolve_free_name and add_file_entry so two threads cannot claim "budget (1).csv" simultaneously. Threads operating in /projects and /srv then run in parallel after passing "/". For cross-directory moves, acquire the two parent directory locks in a fixed lock ordering (always locking the smaller id(node) first) so opposing moves can never deadlock.

Follow-up questions

Similar questions

More Harvey interview questions

All 46 Harvey questions →