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):- Locate the rightmost dot
"."inname. If its index is strictly greater than0,baseis the prefix before that dot andextis everything from that dot to the end (for instance,"bundle.tar.xz"splits into("bundle.tar", ".xz"), and".env.prod"splits into(".env", ".prod")). - If
namecontains no dot, or its only dot sits at index0(such as"Makefile"or".gitignore"),baseisnameitself andextis"".
- Locate the rightmost dot
FileVault(): Create a new vault containing only an empty root folder"/".add_file(path: str) -> str: Store a file at the absolute pathpathand return the final absolute path assigned to it:- Create any ancestor folders along
paththat do not exist yet. - Raise
ValueError(leaving the vault unchanged) ifpathdoes not start with"/", ifpath == "/", or if any ancestor segment alongpathis 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)viasplit_nameand try candidate namesf"{base} ({k}){ext}"fork = 1, 2, 3, ..., picking the smallestk >= 1not yet occupied by a file or subfolder in that folder. Existing numeric suffixes in a requested name are treated as ordinary characters ofbase(duplicating"draft (1).md"produces"draft (1) (1).md").
- Create any ancestor folders along
list_dir(path: str) -> List[str]: Return a list of immediate child names (both files and subfolders) directly insidepath, ordered by ASCII code point. Return[]whenpathdoes 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,000combined calls will be made toadd_fileandlist_dir.
Step-by-step walkthrough
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) insidepathin ASCII order, or[]ifpathdoes not exist or points to a file.Instead of storing flat strings like
"/projects/q4/budget.csv"in one giant set (which would forcelist_dirto scan the entire vault), we model the hierarchy as a tree ofDirectorynodes — 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
Directorynode stores only its immediate children: 1.dirs: maps child directory name to itsDirectoryobject so we can step down a path one segment at a time. 2.files: asetof immediate file names for O(1) collision checks. 3.sorted_names: an ASCII-sorted list of all child names (both directories and files) maintained viabisect.insortsolist_dirnever has to re-sort from scratch. 4.next_suffix: a cache mapping(base, ext)to the nextkto 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 bothself.dirsandself.files. If a subdirectory named"x (1).txt"exists, duplicating"x.txt"skips1and 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) raisesValueError.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)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.innameusingname.rfind("."). 2. Ifdot_index > 0,baseisname[:dot_index]andextisname[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") —extis""andbaseis the entirename!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, ""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.rootand step throughparent_names: - Ifdir_name in node.files, a file blocks the directory path, so we raiseValueError. Notice why this never leaves half-created directories behind:node.filescan only be non-empty on directories that already existed before this call! Once we callnode.add_subdir(...)for the first missing directory, every deeper directory is brand-new and has an emptyfilesset, soValueErrorcan never fire after we mutate the tree. - Otherwise we step intonode.dirs[dir_name]or create it withnode.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])Resolve duplicate names in amortized O(1) time
What happens if we naively check
k = 1, 2, 3, ...from1on every single collision? If a caller adds"/d/a.txt"10,000 times (the operation limit): - The 2nd call checksk = 1(1 check). - The 3rd call checksk = 1, 2(2 checks). - The 10,000th call checksk = 1 .. 9,999(9,999 checks). In total,1 + 2 + ... + 9,999 ≈ 50,000,000string builds and set lookups — several seconds for one test!Now notice a crucial invariant: entries in
FileVaultare never deleted. Once we verify thatk = 1 .. mare all taken innodefor(base, ext), they remain taken forever! So we storenode.next_suffix[(base, ext)] = k + 1after assigning suffixk, and start the next collision search for(base, ext)right atnode.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
kinside thewhileloop 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}"List directory contents in ASCII order
To implement
list_dir(path): 1. Handle"/"explicitly ("/".split("/")is["", ""], whereas root corresponds toself.rootwith zero directory hops). 2. Walkpath.split("/")[1:]throughnode.dirsonly. If a segment is missing — or is a file innode.filesrather than a directory innode.dirs— return[]. 3. Returnlist(node.sorted_names)(a fresh shallow copy so a caller who runsresult.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)! Keepingsorted_namessorted on each insertion viabisect.insortmakes everylist_dira fastO(L + c)slice copy instead of anO(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 nodeTrace 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"]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 walkingpathhashes each segment once in O(L) time. Because files are never deleted,next_suffixnever moves backward: each stored entry in the directory can be skipped by thewhileloop 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 toclist pointers) takes O(c) time.list_dir(path): O(L + c) time. Walkingpathfrom the root inspects O(L) characters, and copying the pre-sortedsorted_nameslist copiescstring 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 innext_suffixper colliding name family.
Edge cases
- Leading-dot hidden files (
".env",".gitignore"): When the only dot sits at index0,rfind(".")returns0(not> 0), soextis""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 index4 > 0and 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).txtwas created as a directory,node.has_entry("x (1).txt")returnsTrue, so duplicating/projects/x.txtsafely skips1and 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, whilelist_dir("/unknown")andlist_dir("/projects/roadmap.md")both return[].
Common mistakes
- Splitting on the first dot (
name.find(".")) or ondot >= 0:find(".")turns"bundle.tar.xz"into"bundle (1).tar.xz", anddot >= 0turns".gitignore"into" (1).gitignore". - Restarting
k = 1from scratch on every collision: Repeatedly adding the same filenameNtimes performsN * (N - 1) / 2hash lookups, timing out atN = 10,000. - Using a blind counter without checking
node.has_entry(...): Handing outk = 1, 2, ...without checking whether"spec (2).md"was already added manually overwrites an existing file. - Checking
name in node.filesinstead ofname 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_namesdirectly instead oflist(node.sorted_names): Exposes internal state so caller mutations corrupt future directory listings.
Alternative approaches
- Balanced search tree per directory (e.g.
sortedcontainers.SortedListor 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_dirwith adirtyflag: Append new names to a plain list in O(1) and marknode.dirty = True, sortingnode.sorted_namesonly whenlist_dirseesnode.dirty == True. This speeds up write-only workloads while keeping repeatedlist_dircalls 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 nokbelownext_suffixcan ever become free again. Oncedelete_fileis allowed, deleted suffixes belownext_suffixopen up reusable gaps; to keep both uploads and deletions at O(log D) time without scanning from1, pairnext_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 freedkvalues, popping from the min-heap first whenever it holds a freek < next_suffix. -
What adjustments are needed to support fast directory moves or renames (such as moving
/srcto/archive/src) without rewriting every descendant path? BecauseDirectorynodes 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'sdirsandsorted_names, resolves any name collision in/archive, and attaches the existingDirectorypointer there in O(depth + c) time. Add aparentpointer on eachDirectoryso the move can walk upward from/archiveto verify you are not moving/srcinside/src/sub(which would detach a cycle from root), and invalidate or update the old parent'snext_suffixentry 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
Directorynode 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.csvlocks root just long enough to fetch or createprojects, locksprojectsbefore releasing root, and holds the write lock onq4across both_resolve_free_nameandadd_file_entryso two threads cannot claim"budget (1).csv"simultaneously. Threads operating in/projectsand/srvthen run in parallel after passing"/". For cross-directory moves, acquire the two parent directory locks in a fixed lock ordering (always locking the smallerid(node)first) so opposing moves can never deadlock.
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?
- What adjustments are needed to support fast directory moves or renames (such as moving `/src` to `/archive/src`) without rewriting every descendant path?
- How would you allow concurrent reads and writes across the vault without serializing every thread behind one global lock?
Similar questions
- Bounded In-Memory File System
- Bounded In-Memory Directory Tree with Auto-Renaming
- Eager-Cached Formula Sheet with Cycle Rejection
- Formula Spreadsheet With Cycle Rejection
- Write-Time Spreadsheet Evaluation with O(1) Reads
- Symbolic Formula Evaluator
More Harvey interview questions
- Formula Spreadsheet With Cycle Rejection Medium
- Bounded In-Memory Directory Tree with Auto-Renaming Medium
- Eagerly Evaluated In-Memory Spreadsheet with Cycle Rejection Medium Pro
- Bounded In-Memory File System Medium Pro
- Write-Time Spreadsheet Evaluation with O(1) Reads Medium Pro
- Tag Merged Keyword Spans in Text Hard Pro
- In-Memory Spreadsheet with Formulas and Cycle Detection Medium Pro
- Multi-Stage In-Memory Spreadsheet with Dependency Graph Medium Pro
- Justifying an Engineering Architecture Choice Under Pushback Medium Pro
- Cloud Drive Architecture: Metadata, Permissions, and Resumable Uploads Medium Pro