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 alongpath, 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 (".","..") raisesValueError. - Capacity limit (
MAX_ENTRIES = 5): Every folder—including the root—may hold at most5immediate entries (files and subfolders combined). Deeper descendants do not count toward an ancestor's limit. Ifadd_filewould push any folder past5direct entries, raiseDirectoryFullError. - File-as-folder conflict: If an intermediate segment along
pathis already a file rather than a directory, raiseNotADirectoryError. - Atomic failure: Whenever
add_fileraisesValueError,NotADirectoryError, orDirectoryFullError, 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 >= 1for that requested name in that folder:- If
"."appears at character index> 0, split at the last"."into(stem, ext); otherwise (such as"README"or".bashrc"), set(stem, ext) = (name, ""). - If
stemalready ends with a parenthesized digit counter(digits)(e.g.,"memo (1)"), format candidatekwithout an extra space asf"{stem}({k}){ext}"(giving"memo (1)(1).md"). Otherwise format with a single space asf"{stem} ({k}){ext}"(giving"memo (1).md"). - Track per-name counters per directory while skipping any candidate names already occupied in that directory.
- If
- Path syntax: Components are separated by
get(path: str) -> List[str]: Return the names of all immediate children (files and subfolders) inside directorypath, sorted in ascending ASCII/Unicode code-point order.- Both
""and"/"denote the root directory. - Raise
ValueErrorfor malformed paths,FileNotFoundErrorifpath(or an ancestor folder) does not exist, andNotADirectoryErrorifpath(or an ancestor segment) refers to a file.
- Both
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 = 5direct entries (files + subdirectories). - Rejected
add_filecalls must be atomic, leaving all directories, files, and per-name counters untouched. - Explain the time and space complexity of
add_fileandget, both underMAX_ENTRIES = 5and for general directory sizec.
Step-by-step walkthrough
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 ("","/"foradd_file,"a//b", or trailing slash"dir/") or relative segment (".","..") raisesValueError. - 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")whena/f.txtis a file), raiseNotADirectoryError. If a leaf file collides with an existing file or folder of the same name (add_file("a")when foldera/exists), auto-rename the new file ("a (1)"). - Capacity and atomicity: every directory (including root) holds at most
5direct entries (files + subfolders). Deeper descendants do not count toward an ancestor's limit. If anadd_filecall would push any directory past5entries, raiseDirectoryFullErrorand create zero intermediate folders. - Case sensitivity and
get(path): names are case-sensitive ("Memo.md"!="memo.md").getreturns sorted immediate child names (""and"/"query root), raisingFileNotFoundErrorfor missing paths andNotADirectoryErrorif the target (or an ancestor) is a file.
- Path syntax: paths look like
Model the directory tree in memory
Represent the hierarchy as a tree of
DirectoryandFilenodes. EachDirectorystores two small hash maps:children: maps each immediate entry name to itsDirectoryorFileobject, making lookup, insertion, andlen(children)O(1) on average.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] = {}Parse and validate paths
Centralize path validation in
_split_pathsoadd_fileandgetenforce 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 raiseValueError.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 partsSplit 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 withname.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 awhileloop until an unused name indirectory.childrenis found, then storek + 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 candidateMake 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:
- Walk existing folders read-only until the first missing folder (or the bottom of
folders), raisingNotADirectoryErrorif an existing entry on the path is aFile. - Check capacity once on
node: iflen(node.children) >= MAX_ENTRIES, raiseDirectoryFullErrorbefore creating any folder or advancing anynext_suffixcounter. - Create and insert: build any missing folders, pick
final_name = _free_name(node, file_name), and insertFile(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])- Walk existing folders read-only until the first missing folder (or the bottom of
List immediate children with get
get(path)handles""and"/"as the root directory, otherwise splitspathand walks down one segment at a time. Checkingisinstance(node, Directory)both inside the loop (when attempting to traverse through a file, such asget("a/f.txt/sub")) and after the loop (when querying a file directly, such asget("a/f.txt")) raisesNotADirectoryErrorin both cases, while a missing segment raisesFileNotFoundError: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)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 createdNotice 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".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/":
add_file("drafts/memo.md"):"drafts"is created at root (1/5entries);"memo.md"is free ->"drafts/memo.md".add_file("drafts/memo.md"):"memo.md"is taken; counter starts at1,"memo (1).md"is free,next_suffix["memo.md"]becomes2->"drafts/memo (1).md".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".add_file("drafts/memo.md"): resumes fromnext_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 validatingpathscans itsPcharacters once; walking existing folders and creating missing folders hashes each path component once (O(P) total characters hashed); checkinglen(node.children) >= 5is O(1); and_free_nameprobes at most 4 candidate names becausenodeholds at most 4 entries before insertion.get(path): O(P) average time withMAX_ENTRIES = 5. Walking the path hashes at mostPcharacters 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
DirectoryandFilenode stores its name once, plus at most one integer innext_suffixper duplicated base name. - Scaling without the 5-entry cap: if a directory can hold
centries,gettakes O(P + c log c) time to sort thecchild names, andnext_suffixkeeps duplicate insertion fast in amortized time (average work per call across a long sequence of calls) becausenext_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")raisesDirectoryFullError, whereasadd_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 raisesDirectoryFullErrorbefore_free_nameruns, sonext_suffixis not incremented. - File vs. folder collisions: traversing through an existing file (
"a/f.txt/g.txt") raisesNotADirectoryError, 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_namesees"f (1).txt"inchildrenand 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_fileis 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_suffixbefore checking capacity: a rejected duplicate call on a full folder then causes a gap in numbering if a slot is later freed. - Trusting
next_suffixwithout checkingdirectory.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_BruteFSintests.py), but everygetand 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 = 1on every duplicate withoutnext_suffix: completely fine whenMAX_ENTRIES = 5(at most 4 checks), though keepingnext_suffixavoids O(c) rescanning per add ifMAX_ENTRIESis 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 leavenext_suffixuntouched so historical numbers are never reused (preventing confusion with old filenames), or parse a deleted"stem (k).ext"and setnext_suffix[base] = min(next_suffix[base], k)so future duplicates fill the lowest freed number while thewhile candidate in childrenloop 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.childrenandDirectory.next_suffixbyname.casefold()while storing the original casing onchild.name. Lookups and duplicate checks then treat"Memo.md"and"memo.md"as the same slot (renaming the second to"Memo (1).md"), whileget(path)returns[child.name for child in ...]sorted in the desired order. - How would you make concurrent
add_fileandgetcalls thread-safe without risking deadlocks or exceeding directory capacity? Checkinglen(node.children) < 5, choosing a free duplicate name, and inserting intonode.childrenmust happen atomically; the simplest design guardsadd_fileandgetwith a singlethreading.RLock. For higher concurrency across disjoint subtrees, place a lock on eachDirectoryand 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 undernode's lock whether another thread just createdfolders[depth]in the meantime.
Follow-up questions
- How should deleting a file or empty directory affect the 5-entry limit and the per-name duplicate counters?
- What changes are needed to enforce case-insensitive collision checks while still displaying each entry's original casing?
- How would you make concurrent `add_file` and `get` calls thread-safe without risking deadlocks or exceeding directory capacity?
Similar questions
- Hierarchical File Vault with Numbered Collision Resolution
- Bounded In-Memory File System
- 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
- Hierarchical File Vault with Numbered Collision Resolution Hard
- 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